referencedrupal-7drupal-modules

Drupal 7 programmatic field definition


I need to programmatically set up a node reference field.

My module successfully creates a and associates a pair of 'CCK' fields to my nodes. One of these fields is a node_reference field. My code is a follows:

$field_ref_name = 'field_custom_reference';
$field = field_info_field($field_ref_name);

if (empty($field)) {
    $field = array(
        "field_name"=>$field_ref_name,
        "label"=>"Custom Reference",
        "type"=>"node_reference",
        "cardinality"=>"1",
        'locked' => TRUE,
    );
    field_create_field($field);
}

$instance = array(
    "field_name"=>$field_ref_name,
    "label"=>"Sequence Reference",
    "type"=>"node_reference",
    "widget"=>array(
        "type"=>"node_reference_autocomplete"
    ),
    "description" => "text describing purpose of this field",
);

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

if( !in_array($type, $field['bundles']['node']) )
    field_create_instance($instance);

Now, the code works but when I edit a node inputting a valid value into the node reference field and attempt to save, I get the following error:

...: this post can't be referenced.

I realized the reason for the error is because the node reference field settings does not have any selected nodes as "Content types that can be referenced".

How can I adjust my code to set referenceable content types?


Solution

  • The reference-able types is a field setting. So it should be put under a "settings" array in the field definition. Something like -

    $field = array(
            "field_name"=>$field_ref_name,
            "label"=>"Custom Reference",
            "type"=>"node_reference",
            "cardinality"=>"1",
            'locked' => TRUE,
            'settings' => array(
              'referenceable_types' => array('article'),
            ),
        );