drupaldrupal-fieldsimagefielddrupal-entities

attach image_field to entity in drupal 7


I use drupal 7, and Entity API to develope a module. I have an entity to record client information. I wish to use image_field to let client upload their logo. So I have this function:

    function silver_client_enable()
{
  field_cache_clear();
  field_associate_fields("silver_client");

  if(field_info_field('logo'))
    return;

  $field = array(
    'field_name' => 'logo',
    'cadinality' => 1,
    'type' => 'image',
    );

    field_create_field($field);

  $instance = array(
    'field_name' => 'logo',
    'entity_type' => 'silver_client',
    'bundle' => 'silver_client',
    'label' => 'Logo',
    'description' => 'Logo',
    'display' => array(
      'default' => array('label' => 'hidden')
    ),
    'settings' => array(
      'file_directory' => '/logo',
    ),
    'widget' => array(
      'type' => 'image_image',
     ),
  );

  field_create_instance($instance);
}

In the entity creation/edit form, I use :

field_attach_form('silver_client', $client, $form, $form_state);

to attch the field.

When I called up this form, the image upload field was corrected displayed. An i can use it to uplod file to serve.

In the form submit function, I save the entity as:

entity_save('silver_client', $client);

However, after I press the save button, the entity table is correctly saved. Field table is not. Both field_data_logo and field_revision_logo are empty.

I believer Entity API looks after the retrieving and saving of attached fields. Can someone tell me what is wrong with my code? Thank you.


Solution

  • You have to write the values back into your entity:

    field_attach_submit('silver_client', $client, $form, $form_state);
    entity_save('silver_client', $client);
    

    http://api.drupal.org/api/drupal/modules!field!field.attach.inc/function/field_attach_submit/7

    And you should validate the field values:

    field_attach_validate('silver_client', $client, $form, $form_state);
    

    http://api.drupal.org/api/drupal/modules!field!field.attach.inc/function/field_attach_validate/7

    Furthermore if you don't want to declare your entity and fields by yourself you might checkout the EntityConstructionKit : http://drupal.org/project/eck which allows to export entity structures with Features just like Views.