我想在我的drupal 7项目中修改一个表单。我希望基于另一个字段值以编程方式activate或停用字段的 requirement状态。
如果字段值为男性,则军事状态字段必须是必需的,但如果是女性,则不需要军事身份,也必须隐藏。
请在这个问题上指导我。
发布于 2018-07-04 12:56:18
你能做的就是不需要军事领域。然后将您自己的验证函数添加到表单中:
$form['#validate'][] = 'my_function_name';然后在你的函数中你可以做一个检查。
function my_function_name*$form, &$form_state){
if($form_state['values']['my_gender_field'] == 'male' && empty($form_state['values']['my_military_field'])){
form_set_error('my_military_field', 'Military field is required');
}
}或者您可以尝试使用表单API中的#state,它具有“必需”选项:https://api.drupal.org/api/drupal/developer!topics!forms_api接口_Cence.html/7.x#状态
发布于 2018-07-15 16:56:32
为了测试满足您需求的解决方案,我为本文使用了一个表单alter。我在代码中添加了很少的注释,希望它们足够了。
/**
* Implements hook_form_FORM_ID_alter().
*/
function my_module_form_article_node_form_alter(&$form, &$form_state) {
$form['gender'] = [
'#type' => 'select',
'#title' => t('Gender'),
'#options' => [
'_none' => t('Please select gender'),
'm' => t('Male'),
'f' => t('Female'),
],
'#default_value' => '_none',
// Ajax info:
'#ajax' => [
// This method returns an array of ajax commands or a form element already prepared.
'callback' => 'my_module_ajax_responder',
// This will tell wich dom id will be replaced with the response.data
'wrapper' => 'military_status_dom_id',
// pretty obiouvs
'method' => 'replace',
'effect' => 'fade',
],
];
// Required property has been set to FALSE as default because no gender has been selected yet
$required = FALSE;
// this if will be ignored on page load, it means no submit has been done yet.
if (!empty($form_state['triggering_element']) && $form_state['triggering_element']['#name'] === 'gender') {
// but if user selects a gender, there will be an ajax submit and this will change
// the required property of the military_status texfield element that is going to be
// rebuilt
$required = $form_state['triggering_element']['#value'] === 'm';
}
// now the actual military_status texfield element.
$form['military_status'] = [
'#prefix' => '',
'#suffix' => '',
'#type' => 'textfield',
'#title' => t('Military status'),
'#required' => $required,
];
}
/**
* Ajax responder.
*/
function my_module_ajax_responder($form, &$form_state) {
// after submit and form rebuild, ajax knows that it has to call this method
// to recover a response data.
// This data will be used to be a replacement (in this case) for the wrapper
// specified in the $form['gender'] element.
return $form['military_status'];
}这里有一些更详细的解释:
https://drupal.stackexchange.com/questions/264230
复制相似问题