简体   繁体   English

drupal 7.如何重构表单数组

[英]drupal 7. how to refactor a form array

I am creating a wizard from the Drupal example file and would like to refactor the segments of code that are repeated when setting up items like options and radios. 我正在从Drupal示例文件创建向导,并希望重构设置选项和单选之类的项目时重复的代码段。

I have already tried a simple function passing "ordinary" and "preferential" but can't find a way to make it work. 我已经尝试过传递“普通”和“优先”的简单函数,但是找不到使它起作用的方法。

Can someone give me an idea of the best way to do this? 有人可以给我一个最佳方法的想法吗?

unfactored code is as below: 未分解的代码如下:

function services_wizard_share_capital_classes($form, &$form_state) {

$form['share_classes']['type_of_class'] = array(
'#type' => 'select',
'#title' => t('What type of share will this class be?'),
'#options' => array(
  1 => t('Ordinary'),
  2 => t('Preferential'),
),
);

$form['ordinary']['share_type'] = array(
'#type' => 'item',
'#description' => t("You chose Ordinary Shares"),
'#states' => array(
  'visible' => array(
    ':input[name="type_of_class"]' => array('value' => '1'),
  ),
),
);

$form['preferential']['share_type'] = array(
'#type' => 'item',
'#description' => t("You chose Preferential Shares"),
'#states' => array(
  'visible' => array(
    ':input[name="type_of_class"]' => array('value' => '2'),
  ),
),
);
return $form;
}

I'm not sure about this being the best way but it's certainly a way to refactor your code: 我不确定这是最好的方法,但肯定重构代码的方法:

function _services_wizard_share_capital_classes_add_el(&$form, $name, $description, $index) {
  $form[$name]['share_type'] = array(
    '#type' => 'item',
    '#description' => t($description),
    '#states' => array(
      'visible' => array(
        ':input[name="type_of_class"]' => array('value' => "$index"),
      ),
    )
  );
}

function services_wizard_share_capital_classes($form, &$form_state) {
  // Other code

  _services_wizard_share_capital_classes_add_el($form, 'ordinary', 'You chose Ordinary Shares', 1);
  _services_wizard_share_capital_classes_add_el($form, 'preferential', 'You chose Preferential Shares', 2);
  // etc...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM