Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

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!

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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