0

Devel noob here. I am writing a module where I need to stash a list of entity ids in a field on a different entity. I've created a field on an entity type programmatically and have it set as field type list(integer), but I'm stuck at actually working with the field data.

How can I add/edit entity ids in the field list programmatically?

For context, this is a Commerce submodule and I am adding to a field on the line item created after submitting an add to cart form. Using dsm($form_data) in a submit handler I added to the add to cart form, I see that the line item object is already stored in $form_data['line_item'] and the data I need to get to would be stored at $form_data['line_item']->field_entity_ids. By this point, I already have my array of ids, I just need some guidance on how to store them properly in the field.

Thanks in advance! :)

1 Answer 1

0

Consider using hook_entity_presave() to populate any auto-generated fields.

In your case, you could do something like:

/**
 * Implements hook_entity_presave().
 */
function example_product_entity_presave($entity, $type) {
  // Set the values for our computed fields.
  switch ($type) {
    case 'commerce_line_item':
      // @todo: get the value for $foo_ids.
      foreach ($foo_ids as $foo_id) {
        $entity->field_entity_ids[LANGUAGE_NONE][] = array(
          'value' => $foo_id,
        );
      }
      break;
  }
}

If you intend to reference any existing entity, you might want to use the Entity Reference module and use an entity reference field instead of an integer field.

1
  • Ah, okay! I was missing having an array with 'value' as key. I think I can avoid writing a presave function since I already have the object used to create the line_item entity in $form_data after validation. (At least I think that's how it works.) Thanks! :)
    – ridgek
    Jan 8, 2014 at 4:34

Your Answer

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

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