How to programmatically create an entity and fill in entity reference fields I'm trying to create an entity that has a number of entity refernce fields, and I'm confused about the best way to do that. so far I've gotten as far as this 

$entity = entity_create('mytype', $values);
$entity-&gt;field_ref = array('und' =&gt; array(0 =&gt; array('value' =&gt; "2")));


Creating the entity works fine, but I can't for the life of me figure out how to fill in the entity references.
The column name for a field isn't always value; in the case of entity references it's target_id if I remember rightly. 

Try this:

$entity = entity_create('mytype', $values);
$entity-&gt;field_ref = array('und' =&gt; array(0 =&gt; array('target_id' =&gt; "2")));