Drupal 7自定义模块表单验证

时间:2016-12-05 07:02:54

标签: drupal drupal-7 hook

我是Drupal 7环境的新手。我想创建一个自定义模块表单并验证它。我在自定义验证表单时遇到问题。请帮忙。我提供以下代码。

<?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;
}

我想在此处添加表单验证。请为此提供解决方案。

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'));
}
?>

1 个答案:

答案 0 :(得分:1)

附加自定义验证:

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

但我认为如果再搜索一下,你可以独自完成;)

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