Tags/topics: 
2
Answers
Vote up!
1
Vote down!

Programatically create an entity reference field for products

There is a great example of how to create a entity reference field here. http://drupal.org/node/1264160
This works if you are focusing on one bundle.
However Commerce Products usually have more than on bundle.
I'm wondering if anyone knows the best way to handle this.

A huge thank you to anyone who could point me in the right direction. (Maybe an example somewhere else ?)

Here the code from the link above

$field = array(
    'field_name' => 'your_field_name',
    'type' => 'entityreference',
    'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    'settings' => array(
      'target_type' => 'your_entity_type',
      'handler_settings' => array('target_bundles' => array('your_entity_bundle')),  // I'm not sure how to handle multiple bundles here
    ),
  );
  field_create_field($field);

  $instance = array(
    'field_name' => 'your_field_name',
    'entity_type' => 'your_instance_entity_type',
    'bundle' => 'your_instance_entity_bundle', // Also is it possible to use multiple bundles here ?
    'label' => 'Your Label',
    'widget' => array(
      'type' => 'options_select',
    ),
    'settings' => array(
      'target_type' => 'your_entity_type',
      'handler_settings' => array('target_bundles' => array('your_entity_bundle')),
    ),
  );
  field_create_instance($instance);
Asked by: bj___
on July 2, 2012

Comments

Did u get that working?
1.How to create fields if the node has more than 1 entity reference fields
2. get more than 1 field from the referenced entity in to the form like eg: SKU and price

- kaizerking on May 1, 2013

2 Answers

Vote up!
1
Vote down!

I think the answer is here : http://numiko.com/labs/2011/programmatically-adding-a-node-reference-fie...

$field = array(
    "field_name"=>"field_field_name",
    "label"=>"Field label",
    "type"=>"node_reference",
    "settings"=>array(
      "referenceable_types"=>array(
        "gallery_image"=>"gallery_image"
      ),
    ),
    "cardinality"=>"-1"
  );

  field_create_field($field);

  $instance = array(
    "field_name"=>"field_field_name",
    "label"=>"Field label",
    "type"=>"node_reference",
    "widget"=>array(
      "type"=>"options_select"
    ),
  );

  $instance["entity_type"] = "node";

  foreach(array("type1", "type2", "type3") as $type){
    $instance["bundle"] = $type; 
    field_create_instance($instance);
  }
Answer by: Anonymous (not verified)
Posted: Sep 10, 2012
Vote up!
0
Vote down!

It appears you have answered your question :)

Josh Miller
Answer by: Josh Miller
Posted: Jul 13, 2012