0
votes

I have a content type with an entity reference field referencing to a custom entity. I need to use a select box because an autocomplete widget is not suitable in my case. However, I cannot load all the entities at once as selectable values because they are too many (72000+ the form won't even load). So I default the entity reference select box to a limited number of values using a views filter and then hide it by default. Then I use an ajax dependent dropdown to show and populate the entity reference select box with filtered down values (I'm using a module that implements hook_form_alter).

My problem is that the form won't validate because now I can select entity reference values which are not the default ones in the select box. So I guess I should control in some way the validation rules of the entity reference field. Is there an easy way to do this? Which hook should I use?

1

1 Answers

0
votes

Set the entity reference field to autocomplete and take it out of the process entirely in your form alter with $form['field_entity_ref']['#access'] = FALSE. This should fix the validation problem. (of course, "field_entity_ref" is what I'm calling your actual reference field.

Add your own validation to the form, if that is still necessary.

Finally, implement hook_node_presave() to manually put the value of your custom ajax drop down box.

So if your custom ajax select box was named my_custom_ref, then it would look something like this:

function mymodule_node_presave($node) {
  if (isset($node->my_custom_ref)) {
    $node->field_entity_ref[$node->language][0]['target_id'] = $node->my_custom_ref;
  }
}