I have a function, my_entity_create(), which returns an empty object for my entity with properties: isnew, name, etc...

I want my fields attached to this empty object so I can set their values. I accomplished this by calling the function below and adding the results to my object in my_entity_create(). Now I can set $my_entity_obj->field_my_field['und'][0]['value'] = 'some value'. I save it with entity_save() and it works.

My question: is there a better way to do this? I'm trying to learn to do things 'the drupal way'... or just the best way if there is not a drupal best practice for a certain task.

function _get_fields_for_bundle($bundle)
    $result = db_select('field_config_instance', 'f')
        ->fields('f', array('field_name'))
        ->condition('entity_type', 'my_entity_type')
        ->condition('bundle', $bundle)

        return array_keys($result);
  • Even better: return array_keys(field_info_instances('entity_type', $bundle));
    – user1750
    Jul 19 '11 at 23:17
  • 1
    Any reason why you want to make it appear that you non created entity has field values?
    – googletorp
    Jul 21 '11 at 8:40
  • I'm tring to achieve the same effect, so that I can programmatically store values to my bundle's fields. How did you merge the return value into your entity object? I get an array keyed numerically with the values of each field name.
    – Arosboro
    Sep 11 '11 at 23:11
  • @Arosboro - you don't need to do this to store values to your bundles fields. Just call field_attach_insert in your entity save function.
    – Felix Eve
    Feb 14 '14 at 12:08

I too was looking for an answer to this question, however you question has provided me with the best answer so far.

My implementation of your solution was to call your function in my entity create function and then loop over the values attaching the fields as empty arrays:

function MY_ENTITY_create($values = array()) {
    $entity = entity_get_controller('MY_ENTITY')->create($values);
    foreach(_get_fields_for_entity('MY_ENTITY') as $field) {
        $entity->{$field} = array();
    return $emtr_safe_check;

function _get_fields_for_entity($entity) {
    $result = db_select('field_config_instance', 'f')
        ->fields('f', array('field_name'))
        ->condition('entity_type', $entity)
        ->condition('bundle', $entity)

        return array_keys($result);

As my entity does not have a bundle, but my module does define several different entities I modified your function slightly to handle loading fields for different entities with bundles of the same name.

I would still be interested to see other peoples solution to this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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