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



1 Answer 1


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...

 * 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(&$query) {
  // check if we got our field
  if(property_exists($query, 'metaData') && $query->metaData['field']['field_name'] == 'field_student_course') {
  • Above causes problems on the edit page since it stops the value loading which is needed to populate the #default_value..
    – davewilly
    May 26, 2014 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.