Drupal webform以编程方式创建复合组件

时间:2012-10-23 09:44:46

标签: drupal-7 custom-component composite-component drupal-webform

我已成功为特定类型的数据创建了自定义webform组件。数据来自不同的部分,因此我需要创建其他但现有的组件类型,这些组件类型将成为我的自定义组件的子组件。 基本上,我试图以编程方式创建一个webform组件的组合。

我的问题是,代码全部成功执行 - 我创建了自定义组件,并得到反馈说我的子组件也已成功创建。 但是,子组件不会显示在我的网络表单中。

在创建自定义组件并将其插入数据库时​​,我尝试通过以下代码创建所有必需的子组件:

function my_module_webform_component_insert($component){
  if($component['type'] == 'my_component'){
    $node = node_load($component['nid']);

    $address_fields = array("my_sub_component1", "my_sub_component2");

    foreach ($address_fields as $key => $address_field) {
        //fetch next available component ID
        $next_id_query = db_select('webform_component')->condition('nid', $component['nid']);
        $next_id_query->addExpression('MAX(cid) + 1', 'cid');
        $next_cid = $next_id_query->execute()->fetchField();

        _create_sub_component($component['nid'], $address_field, $next_cid, $component['cid']);
    }

  }
}

我的_create_sub_component函数定义如下:

function _create_sub_component($nid, $new_component, $cid, $pid){
    $node = node_load($nid);

    $processed_name  = str_replace(' ', '_', strtolower($new_component));
    // Create the webform components array. Not sure if we need all these
    // values, but let's be sure.
    $component = array(
      'cid' => (int)$cid,
      'pid' => 0,#(int)$pid,
      'nid' =>  (int)$node->nid,
      // I don't trust the admin to make a key based on input :)
      'form_key' => $processed_name,
      'name' => $new_component,
      // I want all lines to be numeric type component.
      'type' => 'textfield',
      'value' => '',
      'extra' => array(),
      'mandatory' => '0',
      'weight' => 0,
      'page_num' => 1,
    );

    array_push($node->webform['components'], $component);
    node_save($node);

    drupal_set_message("{$new_component} component successfully created in {$node->title}");
  }

我的猜测是对node_save的调用引起了问题但我不确切知道如何。

1 个答案:

答案 0 :(得分:2)

知道了!

替换:

array_push($node->webform['components'], $component);
node_save($node)

使用:

webform_component_insert($component);