Limit/nullify entity reference query/loading of select options, if using hook form alter to populate with ajax I have added an entity reference field to a profile2 profile entity. The entity type referenced by this field will contain thousands of results (university courses). I have used hook_form_alter to add an ajax callback to the university field which is selected before the course field. Selecting the university first, then populates the course field (which is disabled initially) with the courses available only at the selected university. Since I do not want my courses entity reference field loading thousands of courses on load, I need to nullify the query or hook into the function that populates this field. I have seen entity reference limit module but don't intend to use it.
How can I achieve this? Thanks
I have managed to achieve this using hook_entity_query_alter. I am not sure if this is the best approach.
You can set the limit using the $query->range($start, $length).
Return 1 row.. $query->range(0,1);
See https://api.drupal.org/api/drupal/includes%21entity.inc/function/EntityF...

&lt;?php
/**
 * We don't want to load thousands of courses into the student course entityreference field as
 * we populate it with ajax, so add LIMIT 0 and database should return empty result set
 */
function mymodule_entity_query_alter(&amp;$query) {
  // check if we got our field
  if(property_exists($query, 'metaData') &amp;&amp; $query-&gt;metaData['field']['field_name'] == 'field_student_course') {
    $query-&gt;range(0,0);
  }
}
?&gt;