1

I have a content type that can contain unlimited instances of embedded field collection field_foo, each collection containing two fields: field_foo_bar and field_foo_baz.

I want to modify the node creation form for this content type to pre-populate field_foo with values from the same field on an existing node.

By default the node creation form has:

FIELD FOO

FOO BAR [            ]
FOO BAZ [            ]

...and I would like to set, e.g:

FIELD FOO

FOO BAR [Bar value #1]
FOO BAZ [Baz value #1]

FOO BAR [Bar value #2]
FOO BAZ [Baz value #2]

How can I do this? I feel like I'm missing something straightforward.

I have attempted to simply clone the empty field collection in hook_form_alter() and alter the field_foo_bar and field_foo_baz values to suit, but it causes problems adding/removing rows and tweaking multiple deltas, weights, etc. makes it seem like I'm barking up the wrong tree.

apaderno
  • 28,547
  • 16
  • 75
  • 90
scronide
  • 12,012
  • 3
  • 28
  • 33

2 Answers2

0

As field collections are actually entities, could you use hook_entity_insert() to check if the entity being inserted is an instance of your field collection, and if so set the values.

2pha
  • 9,798
  • 2
  • 29
  • 43
0

hook_form_alter is the correct way to do this. If other problems are occuring it's because your not populating the field correctly or because another module is also editing the fields after you. In the former case check out the format of the filed in hook_node_insert. In the later case change the weight of your module so it fires last and insures your changes overwrite any other modules.

danielson317
  • 3,121
  • 3
  • 28
  • 43
  • The main stumbling block is that Field Collections are actually embedded entities. `hook_node_insert()` only lists an array of field_collection_item entity IDs created at time of submission; there's no direct access to the values of its children there and there are no entity or field instances to refer to on a fresh form. – scronide Jan 11 '13 at 17:38
  • The field information has to be in the form at some points. You might just need to increase your module weight to see it. From what I can see in the code field_collection is a terrible module. Try field_group instead. it uses a much better philosophy for grouping fields together. – danielson317 Jan 11 '13 at 21:35
  • It's certainly there in `hook_form_alter()`, but it's an array of entities which are arrays of fields and it's a opaque mess of values, weights and deltas. There's no basic way say "use the values of this Field Collection as the #default_value of this other Field Collection", which is what I was hoping for. I'm using Field Group as well, but it's the ability to add or remove repeatable multigroups/flexigroups/collections of fields that I need and Field Group explicitly doesn't provide that. – scronide Jan 11 '13 at 23:08