简体   繁体   中英

drupal 7 form, simple check on hook_submit

I'm trying to understand drupal forms by trial and error (not getting along famously with Drupal Documentation), and I'm a bit confused as why doesn't this work:

function sform() {
    $form['password'] = array(
        '#type' => 'password',
        '#title' => 'enter 1234'
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => '1234 and then click',
    );

    $form['#method'] = 'post';

    return $form;
}
function sform_submit($form_id, $form) {
    if (isset($form['values']['password']) && $form['values]']['password'] == "1234") {
        drupal_set_message(t('Success;'), '');
    }
    else {
        drupal_set_message("({$form['values']['password']})", 'warning');
        drupal_set_message(t('Failure'), 'error');
    }
}

I know it all extremely basic and the idea isn't for it to stay in any way like this. As I said I'm just prodding the API to see what works and how.

But the thing is, the basic check is that the "password" field exists and is equal to "1234". And it fails every time. In the failure branch I spit out what value I've got from "password", and I see that it was "1234" nonetheless...

Is there some very obvious reason why the comparison between $form['values']['password'] and "1234" shouldn't be working as I intend here???

You have a typo on your if test:

$form['values]']['password']
//should be
$form['values']['password']

Also it looks like you have your functions setup incorrectly, take a look here: https://api.drupal.org/api/drupal/includes!form.inc/group/form_api/7

You should be passing $form and $form_state (by reference) when using forms.

Taken from link above:

function my_module_example_form($form, &$form_state) {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}
function my_module_example_form_validate($form, &$form_state) {
  // Validation logic.
}
function my_module_example_form_submit($form, &$form_state) {
  // Submission logic.
}

Plus your menu hook should call drupal_get_form as the callback and your function name as the page arguements.

$items['sform'] = array(
    'title' => 'My Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sform'),
    'access arguments' => array('some rule'),
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM