6

ノード タイプにアタッチされたフィールド コレクションがいくつかあり、Drupal のフォーム API を使用してカスタム フォームを作成中です。

これらのフィールド コレクション フィールドをフォームにロードするにはどうすればよいですか? hook_formhook_field、または他のもの を使用する必要がありますか?

カーディナリティが無制限のフィールド コレクションであるフォーム要素を記述する簡単な例を教えてもらえますか?

4

3 に答える 3

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;
}

サンプル送信ハンドラー @see in submit ハンドラーここで指定された例を使用できます

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 );
    }
  }
  ...
}
于 2012-11-28T08:46:24.473 に答える