0

I've created a custom entity with bundle and added 3 fields to the bundle(namely recipient, sender, flag). How can I add values to it programmatically. Any help would be appreciated.

Thanks

2

One approach is using entity_metadata_wrapper:

The Entity API provides wrapper classes you may use to make dealing with the values of an entity's properties and fields easier. Wrappers make it easier to get and set the values of fields and properties as well as to programmatically retrieve additional information about these elements and iterate over lists of values in a consistent manner.

Example:

$entity_wrapper = entity_metadata_wrapper('myentity', $id);
$var = $entity_wrapper->field_flag->value() + 1;
$entity_wrapper->field_flag->set($var);
$entity_wrapper->save();
  • Yes @jorgetutor, this was my thought, but i think in order to wrap your entity you have to have an existing entity(the second param in the entity_metadata_wrapper). My problem is i want to add a new value. – adevms Apr 13 '14 at 12:55
  • The second parameter also can be an ID. You can use the set() method to add a new value to your entity and then save it. – jorgetutor Apr 13 '14 at 13:39
1

So this is one way to do it. You have to build an object, then assign values to the fields you've created and call the entity_save: ("Blocking" entity type and an bundle with the same name).

$entity = new stdClass(); 
$entity->type = 'blocking';
$entity->field_recipient[LANGUAGE_NONE][0]['uid'] = $user->uid;
$entity->field_sender[LANGUAGE_NONE][0]['uid'] = $user_to_block;
$entity->field_blocked[LANGUAGE_NONE][0]['value'] = 1;

entity_save('blocking',$entity);

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.