这是我想出的最简单的解决方案。这基本上有 2 个部分:(1.) 以编程方式更改表单的显示,以及 (2.) 使用 GUI 更改内容的显示。
(1.) 首先,我使用hook_form_alter()以编程方式创建条件字段集并向其中添加现有字段。代码如下所示。
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'FORM_ID_node_form') {
// programmatically create a conditional fieldset
$form['MYFIELDSET'] = array( // do NOT name the same as a 'Field group' fieldset or problems will occur
'#type' => 'fieldset',
'#title' => t('Conditional fieldset'),
'#weight' => intval($form['field_PARENT']['#weight'])+1, // put this fieldset right after it's "parent" field
'#states' => array(
'visible' => array(
':input[name="field_PARENT[und]"]' => array('value' => 'Yes'), // only show if field_PARENT == 'Yes'
),
),
);
// add existing fields (created with the Field UI) to the
// conditional fieldset
$fields = array('field_MYFIELD1', 'field_MYFIELD2', 'field_MYFIELD3');
$form = MYMODULE_addToFieldset($form, 'MYFIELDSET', $fields);
}
}
/**
* Adds existing fields to the specified fieldset.
*
* @param array $form Nested array of form elements that comprise the form.
* @param string $fieldset The machine name of the fieldset.
* @param array $fields An array of the machine names of all fields to
* be included in the fieldset.
* @return array $form The updated form.
*/
function MYMODULE_addToFieldSet($form, $fieldset, $fields) {
foreach($fields as $field) {
$form[$fieldset][$field] = $form[$field]; // copy existing field into fieldset
unset($form[$field]); // destroy the original field or duplication will occur
}
return $form;
}
(2.) 然后我使用字段组模块来更改内容的显示。我通过转到我的内容类型并使用“管理显示”选项卡创建一个字段组并将我的字段添加到其中来做到这一点。这样,这些字段将在表单和保存的内容上显示为属于同一组。