需要一个关于将字段集合附加到drupal表单的示例 - drupal 7

Joh*_*n K 6 drupal drupal-7 drupal-modules

我有一些附加到节点类型的字段集合,我正在使用Drupal的Form API编写自定义表单.

如何将这些字段集合字段加载到表单中?我应该使用hook_form,hook_field或其他什么?

有人能给我一个简单的例子来编写一个表单元素,这是一个具有无限基数的字段集合吗?

D34*_*man 0

我能够使用以下代码来加载字段集合表单。我添加了额外的注释并删除了从 $form_state['values'] 变量中查找字段值的自定义逻辑。

function mymodule_custom_form($form, $form_state, $args ){
  $form = array();
  $type = $args['type'];
  $id = $args['id'];
  module_load_include('inc', 'field_collection', 'field_collection.pages');
  if(!empty($entity->field_comments[LANGUAGE_NONE][0]['value']) ){
    $field_collection_item = field_collection_item_load($entity->field_comments[$entity->language][0]['value'], TRUE);
    $output = drupal_get_form('field_collection_item_form', $field_collection_item);
  }else{
    $output = field_collection_item_add('field_comments', 'node', $entity->nid);
  }  
  dpm($output);
  // If you want to use field collection form submit handlers as is, just return the below   
  // In case you want to use your own custom submit handlers then do modify the $output array as seems fit.
  $form['field_collection_element'] = $output;
  // You may also attach the $output array to your custom form array. Make sure you handle submit handlers properly

  return $form;
}
Run Code Online (Sandbox Code Playgroud)

提交处理程序中的示例提交处理程序 @see 您可以使用此处给出的示例

function mymodule_custom_form_submit( $form, $form_state ){
  ...
  if(empty($item_id)){
    $field_collection_item = entity_create('field_collection_item', array('field_name' => $field_name ));
    $field_collection_item->setHostEntity('node', $node);
  }
  else {
    $items = entity_load('field_collection_item', array($item_id));
    $field_collection_item = $items[$item_id];
  }
  if( is_object($field_collection_item)){
    // for references.
    $field_collection_item->field1[$node->language][0]['target_id'] = $field1_val;
    // normal values
    $field_collection_item->field2[$node->language][0]['value'] = $field2_val;
    $field_collection_item->field3[$node->language][0]['value'] = $field3_val;
    if(empty($item_id)){
      $field_collection_item->save( FALSE );
    }
    else{
      $field_collection_item->save( TRUE );
    }
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)