简体   繁体   中英

Drupal 7 custom module form validate

I'm new to Drupal 7 enviroment. I want to create a custom module form and validate it. I'm facing problems in custom validating the form. Please help. I am providing the code below.

<?php 
//implementing hook permissions
function userform_2_permission(){
    return array(
        'submit userform_2' => array(
            'title' => t('Submit Userform_2'),
            'description' => t('Submit username in the field'),
    ),
 );
}

// implementing hook menu
function userform_2_menu(){
    $items = array();
    $items['userform_2'] = array(
        'title' => 'Userform 2',
        'description' => 'Input the username',
        'type' => MENU_NORMAL_ITEM,
        'access arguments' => array('access userform_2'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('userform_2_form'),
    );
    return $items; 
}

// implementing form

function userform_2_form($form,&$form_state){

    $form['username'] = array(
        '#type' => 'textfield',
        '#title' => t('Username'),
        '#description' => t('Please provide your username'),
        '#size' => 60,
        '#maxlength' => 128,

    );

    $form['password'] = array(
        '#title' => t('Password'),
        '#type' => 'password', // it provdes the password + password_confirm field
        '#size' => 60,
        '#description' => 'Please provide a password',
        '#maxlength' => 128,

    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Login'),
    );

    return $form;
}

I want to add form validation here. Please provide the solution for this.

function useform_2_form_validate($form,&$form_state){
    // please provide solution 
}

// implementing submit handler
function userform_2_form_submit($form, &$form_state){
    $u_id = db_insert('userform_2') -> fields(array(
            'username' => $form_state['values']['username'],
            'password' => $form_state['values']['password'],
        )) ->execute();

    drupal_set_message(t('the username has been added'));
}
?>

Attach custom validation :

$form['#validate'][] = 'useform_2_form_validate';

But I think if you search a little more you can do it alone ;)

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x/#validation

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