我能够使用以下代码加载字段收集表单。我添加了额外的注释并删除了从 $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;
}
一个示例提交处理程序@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 );
}
}
...
}