The auto complete widget for entityreference does not work with crm_core_contact entity type as it does not return the appropriate result when typing in the autocomplete textfield, this is due to the fact entityreference below:

crm_core_contact_ui_entityreference.inc

    if (isset($match)) {
      $entity_info = entity_get_info($this->field['settings']['target_type']);
      if (isset($entity_info['entity keys']['label'])) {
        $query->propertyCondition($entity_info['entity keys']['label'], $match, $match_operator);
      }
    }

The entity reference field tries to fetch the ID of the entity type (but we have no $entity_info['entity keys']['label'] defined.

The patch is attached as well as the new entityreference class i created to fix this problem

crm_core_contact_ui_entityreference.inc


if (!module_exists('entityreference')) {
  exit();  
}

/**
 * Overwrite entity reference handler class so autocomplete widget works with crm_core_contact
 */
class EntityReference_SelectionHandler_Generic_crm_core_contact extends EntityReference_SelectionHandler_Generic {
  /**
   * Implements EntityReferenceHandler::getReferencableEntities().
   */
  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $options = array();
    $entity_type = $this->field['settings']['target_type'];

    $query = $this->buildContactFieldQuery($match, $match_operator);
    if ($limit > 0) {
      $query->range(0, $limit);
    }

    $results = $query->execute();

    if (!empty($results[$entity_type])) {
      $entities = entity_load($entity_type, array_keys($results[$entity_type]));
      foreach ($entities as $entity_id => $entity) {
        $options[$entity_id] = $this->getLabel($entity);
      }
    }

    return $options;
  }
  
  /**
   * Build an EntityFieldQuery to get referencable entities.
   */
  public function buildContactFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', $this->field['settings']['target_type']);
    if (!empty($this->field['settings']['handler_settings']['target_bundles'])) {
      $query->entityCondition('bundle', $this->field['settings']['handler_settings']['target_bundles'], 'IN');
    }
    if (isset($match)) {
        // @todo, we must choose from the field setting on what field to use from the contact entity
        // we might also search by given name as well
        $query->fieldCondition('contact_name', 'family', $match, 'CONTAINS');
    }

    // Add a generic entity access tag to the query.
    $query->addTag($this->field['settings']['target_type'] . '_access');
    $query->addTag('entityreference');
    $query->addMetaData('field', $this->field);

    // Add the sort option.
    if (!empty($this->field['settings']['handler_settings']['sort'])) {
      $sort_settings = $this->field['settings']['handler_settings']['sort'];
      if ($sort_settings['type'] == 'property') {
        $query->propertyOrderBy($sort_settings['property'], $sort_settings['direction']);
      }
      elseif ($sort_settings['type'] == 'field') {
        list($field, $column) = explode(':', $sort_settings['field'], 2);
        $query->fieldOrderBy($field, $column, $sort_settings['direction']);
      }
    }
    return $query;
  }
}

Comments

ygerasimov’s picture

Category: bug » task
Status: Needs review » Needs work

I cannot reproduce the problem here. I have entityreference latest rc1 version. Created three contacts (different types) and entityreference field on the node. I can create references from the node to all contacts.

There is problem that contacts are not shown on the node view page. But that is different problem.

Patch is not well formed (it has only changes in .info file).

Please advise how to reproduce the problem?

dealancer’s picture

I have ported patch so it can work good with recent version of Entity Reference, also updated naming and added search by other name subfields (given, middle, etc), it was tricky, though.

Committed:
http://drupalcode.org/project/crm_core.git/commit/2e007fa
http://drupalcode.org/project/crm_core.git/commit/f5160cc

I used part of code from Name module, but it this code needs to be improved here and there, see http://drupal.org/node/1369618#comment-6278744. So I am not closing this issue.

dealancer’s picture

Here is a fix that allows to use own later hook when implementing contact search in entity reference, this could be
a part of solution for #1701926: Name field settings are generic to all contact types.

philipz’s picture

I don't know if this is right place to write this but the issue topic is perfect :)

I'm trying to add activity to the contact and I'm getting this ajax error:
StatusText: Service unavailable (with message)
ResponseText: PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'crm.field_data_contact_name' doesn't exist:

I have replaced the default core crm contacts with my own and I guess this is because I've got no such field anymore but what if I wanted to reference my contact by other fields or do I have to add this field for now to make it work? Is this Entity Reference or CRM Core problem?

dealancer’s picture

Looks like it is related to issue: http://drupal.org/node/1586366, for now just add new contact_name field.

dealancer’s picture

Priority: Normal » Major
pingers’s picture

perhaps a custom views field handler to display crm core contact label will work better in default views?

then we're not relying on name field specifically in views.

Anonymous’s picture

I have been running into a lot of issues with how to present entity references.

What might make sense is a default callback for entity references that format the name of the contact and pass back the entity id. It could be something users could customize as they go along.

rosk0’s picture

Assigned: ygerasimov » Unassigned

Not changing status, but this problem is currently solved.

luckyape’s picture

My deployment running all the latest version produces the following query

SELECT crm_core_contact.contact_id AS contact_id, crm_core_contact.type AS crm_core_contact_type, crm_core_contact.changed AS crm_core_contact_changed, field_data_contact_name.contact_name_title AS contact_name, 'crm_core_contact' AS field_data_contact_name_crm_core_contact_entity_type
FROM 
crm_core_contact crm_core_contact
LEFT JOIN crm_core_contact_type crm_core_contact_type ON crm_core_contact.type = crm_core_contact_type.type
LEFT JOIN field_data_contact_name field_data_contact_name ON crm_core_contact.contact_id = field_data_contact_name.entity_id AND (field_data_contact_name.entity_type = 'crm_core_contact' AND field_data_contact_name.deleted = '0')
WHERE ((( (field_data_contact_name.contact_name_title LIKE '%M%' ESCAPE '\\') ))AND(( (crm_core_contact_type.disabled = '0') AND (crm_core_contact.type IN  ('person')) AND (LOWER(CONCAT(' ', COALESCE(field_data_contact_name.contact_name_title, ''), ' ', COALESCE(field_data_contact_name.contact_name_given, ''), ' ', COALESCE(field_data_contact_name.contact_name_middle, ''), ' ', COALESCE(field_data_contact_name.contact_name_family, ''), ' ', COALESCE(field_data_contact_name.contact_name_generational, ''), ' ', COALESCE(field_data_contact_name.contact_name_credentials, ''))) LIKE '% %') )))
ORDER BY crm_core_contact_changed DESC
LIMIT 10 OFFSET 0

The query is wrong in a couple of places - the first condition should not be present and the search string is not being passed into the query, see "LIKE '% %'"

This query will only return items with 'title' values within the name widget.

rosk0’s picture

Priority: Major » Normal
Status: Needs work » Postponed (maintainer needs more info)

As i mentioned before, the problem is already fixed.
@luckyape: please ensure that you are using stable release of crm_core and other modules.
If you still experience problems feel free to post here, but with more info(use cases, module versions, etc.).

pingers’s picture

I.e. use the "development" branch.

pingers’s picture

Status: Postponed (maintainer needs more info) » Needs review

This was broken. See attached which finds the query base table alias automatically and join against the crm_core_contact table.

This seems to fix the problem when I add some contacts, add an entityreference field to a node using autocomplete and try to use it at node/add/{type}.

pingers’s picture

Ugh, attach the patch.

tintisha_andy’s picture

I've applied pingers' patch on comment #14 and it has fixed the autocomplete widget for a contact entity reference. However it has broken the autocomplete widget for adding a relationship.

I've got a 'Members' contact type and an 'Organisations' contact type and created an 'Employee of' relationship type. Since applying the patch the add a relationship autocomplete widget throws a long javascript error.

Reversing the patch solves the error but then obviously the original issue is still present.

Anonymous’s picture

Can someone explain the problem a little more clearly? I can't seem to reproduce it, and I don't want to leave this open without a resolution.

Testing on an activity type with an entity reference field, I was able to successfully add contacts, save the activity, and see the contacts on the activity page. Is this not the issue?

pingers’s picture

It's about removing the assumption that autocomplete works by "name". This is true for an individual, but for an organisation, this is not the case.

Anonymous’s picture

Oh, what other field does an organization use?

My understanding was that we store organization name in the name field, in the last name part.

pingers’s picture

It was from a long time ago... I remember a time when we used a text field for household and organisations. This is probably no longer valid, given I could successfully use the autocomplete for relations and entityreferences.

I did see that organisations and households require a first and last name. This is another issue though.

Anonymous’s picture

Let me look at that again, but the last time I checked the name module could be set up with different required fields for each bundle in the entity.

  • Commit bc3ebee on 7.x-1.x, development, import by dealancer:
    Issue #1595458 by xcf33, dealancer: Entity Reference autocomplete widget...
  • Commit f5160cc on 7.x-1.x, development, import by dealancer:
    Issue #1595458 by dealancer: using fulltext query when  search for...
  • Commit e2473e0 on 7.x-1.x, development, import by dealancer:
    Issue #1595458: added ability to use own query alter hook for searching...

  • Commit bc3ebee on 7.x-1.x, development, import, activity_pages by dealancer:
    Issue #1595458 by xcf33, dealancer: Entity Reference autocomplete widget...
  • Commit f5160cc on 7.x-1.x, development, import, activity_pages by dealancer:
    Issue #1595458 by dealancer: using fulltext query when  search for...
  • Commit e2473e0 on 7.x-1.x, development, import, activity_pages by dealancer:
    Issue #1595458: added ability to use own query alter hook for searching...
jelle_s’s picture

StatusFileSize
new1.34 KB

Rerolled against 7.x-0.x

  • dealancer committed bc3ebee on og_integration
    Issue #1595458 by xcf33, dealancer: Entity Reference autocomplete widget...
  • dealancer committed e2473e0 on og_integration
    Issue #1595458: added ability to use own query alter hook for searching...
  • dealancer committed f5160cc on og_integration
    Issue #1595458 by dealancer: using fulltext query when  search for...

  • dealancer committed bc3ebee on mail
    Issue #1595458 by xcf33, dealancer: Entity Reference autocomplete widget...
  • dealancer committed e2473e0 on mail
    Issue #1595458: added ability to use own query alter hook for searching...
  • dealancer committed f5160cc on mail
    Issue #1595458 by dealancer: using fulltext query when  search for...
rosk0’s picture

Status: Needs review » Fixed

Was fixed by eeae84b6d074483c668236eb89b58b99ee6807b9.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.