我在自定义模块中创建了一个表单 我尝试为文本字段'distance [postal_code]'
添加验证但没有用!
谁能帮帮我?
Hook_menu:
function location_search_menu() {
$items = array();
$items['markten'] = array( //this creates a URL
'title' => 'Markten, nog toegankelijker!', //page title
'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed. for a form, use drupal_get_form
'page arguments' => array('location_search_form'), //put the name of the form here
'access callback' => TRUE
);
return $items;
}
表格:
function location_search_form($form, &$form_state) {
$form['#prefix'] = '<div id="postal-code-search"><h2>Markten vandaag in de buurt...</h2>';
$form['#sufix'] = '</div>';
$form['#attributes'] = array('id' => 'postal-code-form');
$form['#method'] = 'get';
$form['#action'] = '/location-list'; // make url
$form['distance[postal_code]'] = array(
'#type' => 'textfield', //postal code field
'#size' => 10,
'#maxlength' => 10,
'#required' => TRUE, //make this field required
'#attributes' =>array('placeholder' => t('Postal code')),
);
$form['submit_button'] = array(
'#type' => 'submit',
'#value' => t('Search'),
'#name' => '', // unset 'op'
);
return $form;
}
验证:
function location_search_validate($form, &$form_state) {
$pc = $form_state['values']['distance[postal_code]'];
if(empty($pc) || $pc == '') {
form_set_error('distance[postal_code]', t('Postal code is required!'));
}
}
答案 0 :(得分:1)
尝试:
$form['distance[postal_code]'] = array(
'#type' => 'textfield', //postal code field
'#size' => 10,
'#maxlength' => 10,
'#required' => TRUE, //make this field required
'#element_validate' => array('empty_element_validation'),
'#attributes' =>array('placeholder' => t('Postal code')),
);
function empty_element_validation($element, &$form_state, $form) {
if (empty($element['#value'])) {
//form_set_error('distance[postal_code]', t('Postal code is required!'));
form_error($element, t('Postal code is required!'));
}
}
答案 1 :(得分:0)
我发现问题出现在这段代码中:
...
$form['#method'] = 'get';
$form['#action'] = '/location-list';
...
这段代码:
...
$form['#after_build'][] = 'location_search_form_modify';
...
function location_search_form_modify($form){ // remove form_token, form_build_id, form_id from url
unset($form['form_token']);
unset($form['form_build_id']);
unset($form['form_id']);
return $form;
}
...
如果表单已提交,则会重定向到“获取”网址,并忽略验证