1

In a Drupal 7 site, I have created a new entity called "atomyx_portal_metadata". This entity works great in all respects. I allow people to define their own entity types (much as you can create your own node types).

While allowing someone to fill out a form to enter values for such an entity type (much like filling out the form for an article for example), I use the following code:

// Get the metadata blob for this job
$metadata = atomyx_portal_metadata_load($job->mid);

// Save the metadata entity in our form array so we can pick it up in the validation routine
$form['metadata'] = array(
    '#type' => 'value',
    '#value' => $metadata,
);

// Add form elements for all attached fields
field_attach_form('atomyx_portal_metadata', $metadata, $form['container'], $form_state );

The "field_attach_form" call correctly adds all necessary form elements for editing the form, and I can validate and save those values correctly in the database afterwards. However, the form elements do not contain the default values defined in the field definition and I don't seem to be able to figure out how to correctly fill in the default values of all fields into the form.

I assume I could do this by looping over all fields myself, and trying to figure out with help of the field api what the default value for that field in the given entity-type is, but that seems like a very ... un-field-api-ish way to do it.

Is there something I'm missing? Is there a call in the field attach api that would allow me to have the fields filled in with default values correctly?

Any and all hints greatly appreciated!

1 Answer 1

0

I think I found what the problem was. From the documentation and Drupal code it became clear that what I did in the form ought to be correct: field_attach_form should properly load all fields.

Which led to the fact that it must be the creation of the entity that is incorrect and not the actual form loading of the entity fields.

While examining the entity class I use, I came to the conclusion that the example code I used to build this entity wasn't complete. Upon first creating an instance of the entity, the code should not only save the entity data itself, but it should also call field_attach_insert. Just as it should call field_attach_update whenever the metadata entity exists already but is saved again (updated).

Upon adding this, the field_attach_form call now "magically" loaded the proper default values into the form.

Eureka.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.