Group entity reference field by a field on those entities I have a content type of Location that has a list (text) field with options for Full Service or Quick Stop.

On another content type, I have an entity reference field that pulls in all the locations (using a select list widget).

On the node creation/edit form, I am trying to group those locations with optgroups into Full Service and Quick Stop based on the value of the nodes in the entity reference field (i.e. a location with field_location_type of "Quick Stop" would go into the Quick Stop optgroup).

Right now I am manually sorting them with the following, but it would be nice to do it automatically via my field_location_type field so that new options are automatically added.

$form['field_location']['und']['#options'] = array (
   'Full Service' =&gt; array(
      19 =&gt; 'Main Street',
      20 =&gt; 'Oak Hills',
      21 =&gt; 'Cherry Trail',
    ),
    'Quick Stop' =&gt; array(
      22 =&gt; 'Montreal',
      26 =&gt; 'Washington Place',
    ),
);
Use the module Entityreference View Widget and set up a view with grouping based on location type.

Alternatively, using custom code: 

// Grab our list of all possible location types.
$location_types = list_allowed_values(field_info_field("field_location_type"));
$options = array();

// Cycle through each location type.
foreach ($location_types as $location_type_key =&gt; $location_type) {
  // Find all the nodes that are set to use this location type.  
  // You may need to adjust this query if you need to limit it to only nodes of a specific type in the event you use field_location_type on other content types that you don't want showing up in this list.
  $efq = new EntityFieldQuery();
  $locations = $efq-&gt;entityCondition('entity_type', 'node')
    -&gt;fieldCondition('field_location_type', 'value', $location_type_key)
    -&gt;propertyOrderBy('title', 'DESC')
    -&gt;execute();

  // If any nodes are found with this location type, add them to the options array under the appropriate location type
  if (!empty($locations['node'])) {
    foreach($locations['node'] as $location) {
      $options[$location_type][$location-&gt;nid] = entity_label('node', node_load($location-&gt;nid));
    }
  }
} 

$form['field_location']['und']['#options'] = $options;