Limit options of OG audience field properly

Public

Organic Groups does not allow to use another entity selection mode (like output of an entityreference view) to limit options available in a group reference field. Here is detailed example about how to limit it, in this case for a certain content type only.
(It should not be done in hook_field_widget_options_select_form_alter(), etc.)

</> CopyGet raw version
php
  1. <?php
  2.  
  3. /**
  4.  * Implements hook_query_TAG_alter().
  5.  *
  6.  * Limit OG_AUDIENCE_FIELD field's options on Import CT to display only those
  7.  * products which can use the importer.
  8.  */
  9. function MY_MODULE_query_og_alter(QueryAlterableInterface $query) {
  10. /** @var EntityReference_SelectionHandler_Generic_node $handler */
  11. $handler = $query->getMetaData('entityreference_selection_handler');
  12. if ($handler && $handler->instance['entity_type'] == 'node' && $handler->instance['bundle'] == 'import') {
  13. $query->leftJoin('field_data_field_import_importer_disabled', 'iid', 'node.nid = iid.entity_id AND node.type = iid.bundle AND iid.entity_type = :type', array(':type' => $handler->instance['entity_type']));
  14. $or = db_or();
  15. $or->isNull('iid.field_import_importer_disabled_value');
  16. $or->condition('iid.field_import_importer_disabled_value', TRUE, '<>');
  17. $query->condition($or);
  18. }
  19. }