CRM-13966 - Wire up contact api to getlist api
authorColeman Watts <coleman@civicrm.org>
Tue, 11 Feb 2014 17:40:53 +0000 (09:40 -0800)
committerColeman Watts <coleman@civicrm.org>
Tue, 11 Feb 2014 17:55:19 +0000 (09:55 -0800)
CRM/Core/Form.php
api/v3/Contact.php
api/v3/Generic/Getlist.php
js/Common.js
tests/phpunit/api/v3/TagTest.php

index a4deeb41386f78a6524900a69ff22b3198d43da8..d1833387985c945a38c2a79923273ecdea8f0db7 100644 (file)
@@ -1319,20 +1319,15 @@ class CRM_Core_Form extends HTML_QuickForm_Page {
           $field->setValue($val);
         }
         $result = civicrm_api3($entity, 'getlist', array('params' => array('id' => $val)));
-        if (!empty($result['values'])) {
-          foreach($result['values'] as $row) {
-            $data[] = array('id' => $row['id'], 'text' => $row['label']);
-          }
-        }
         if ($field->isFrozen()) {
           $field->removeAttribute('class');
         }
-        if ($data) {
+        if (!empty($result['values'])) {
           // Simplify array for single selects - makes client-side code simpler (but feels somehow wrong)
           if (empty($select['multiple'])) {
-            $data = $data[0];
+            $result['values'] = $result['values'][0];
           }
-          $field->setAttribute('data-entity-value', json_encode($data));
+          $field->setAttribute('data-entity-value', json_encode($result['values']));
         }
       }
     }
index 97a3e26cf945fd88d53e799ed8dc262a37a224a1..8dd4f7750d139923d9f3d7b498953be44e4589b0 100644 (file)
@@ -884,3 +884,74 @@ WHERE     $whereClause
   return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao);
 }
 
+
+/**
+ * Overrides _civicrm_api3_generic_getlist_params.
+ *
+ * @param $request array
+ */
+function _civicrm_api3_contact_getlist_params(&$request) {
+  // get the autocomplete options from settings
+  $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
+    CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+      'contact_autocomplete_options'
+    )
+  );
+
+  // get the option values for contact autocomplete
+  $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
+
+  $list = array();
+  foreach ($acpref as $value) {
+    if ($value && !empty($acOptions[$value])) {
+      $list[] = $acOptions[$value];
+    }
+  }
+  // If we are doing quicksearch by a field other than name, make sure that field is added to results
+  $field_name = CRM_Utils_String::munge($request['search_field']);
+  // Unique name contact_id = id
+  if ($field_name == 'contact_id') {
+    $field_name = 'id';
+  }
+  // phone_numeric should be phone
+  $searchField = str_replace('_numeric', '', $field_name);
+  if(!in_array($searchField, $list)) {
+    $list[] = $searchField;
+  }
+  $request['params']['options']['return'] = $list;
+  $request['params']['options']['sort'] = 'sort_name';
+  // Contact api doesn't support array(LIKE => 'foo') syntax
+  $request['params'][$request['search_field']] = $request['input'];
+}
+
+/**
+ * Overrides _civicrm_api3_generic_getlist_output
+ *
+ * @param $result array
+ * @param $request array
+ *
+ * @return array
+ */
+function _civicrm_api3_contact_getlist_output($result, $request) {
+  $output = array();
+  if (!empty($result['values'])) {
+    foreach ($result['values'] as $row) {
+      $data = array(
+        'id' => $row[$request['id_field']],
+        'label' => $row[$request['label_field']],
+      );
+      $description = array();
+      foreach ($request['params']['options']['return'] as $item) {
+        if (!strpos($item, '_name') && !empty($row[$item])) {
+          $description[] = $row[$item];
+        }
+      }
+      $data['description'] = implode(' :: ', $description);
+      if (!empty($request['image_field'])) {
+        $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
+      };
+      $output[] = $data;
+    }
+  }
+  return $output;
+}
index 84412592e9bf98d2548976bc978af3daf65e6d30..3d181b7917a51891722a5bfecac5cc98cf41ea82 100644 (file)
@@ -122,8 +122,12 @@ function _civicrm_api3_generic_getList_defaults($entity, &$request) {
  */
 function _civicrm_api3_generic_getlist_params(&$request) {
   $fieldsToReturn = array($request['id_field'], $request['label_field']);
-  !empty($request['image_field']) && $fieldsToReturn[] = $request['image_field'];
-  !empty($request['description_field']) && $fieldsToReturn[] = $request['description_field'];
+  if (!empty($request['image_field'])) {
+    $fieldsToReturn[] = $request['image_field'];
+  }
+  if (!empty($request['description_field'])) {
+    $fieldsToReturn[] = $request['description_field'];
+  }
   $request['params']['options']['return'] = $fieldsToReturn;
 }
 
@@ -139,12 +143,17 @@ function _civicrm_api3_generic_getlist_output($result, $request) {
   $output = array();
   if (!empty($result['values'])) {
     foreach ($result['values'] as $row) {
-      $output[] = array(
+      $data = array(
         'id' => $row[$request['id_field']],
         'label' => $row[$request['label_field']],
-        'description' => isset($request['description_field']) && isset($row[$request['description_field']]) ? $row[$request['description_field']] : NULL,
-        'image' => isset($request['image_field']) && isset($row[$request['image_field']]) ? $row[$request['image_field']] : NULL,
       );
+      if (!empty($request['description_field'])) {
+        $data['description'] = isset($row[$request['description_field']]) ? $row[$request['description_field']] : '';
+      };
+      if (!empty($request['image_field'])) {
+        $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
+      };
+      $output[] = $data;
     }
   }
   return $output;
index 2f06ba67013e5d961daf887e8dc6a20ffff14b3c..d2bdace84b2d58eda9de6601ba64700c1b2779a3 100644 (file)
@@ -273,6 +273,17 @@ CRM.validate = CRM.validate || {
     });
   };
 
+  CRM.utils.formatSelect2Result = function(row) {
+    var markup = '<table class="crm-select2-row"><tr>';
+    if (row.image !== undefined) {
+      markup += '<td class="crm-select2-row-image"><img src="' + row.image + '"/></td>';
+    }
+    markup += '<td class="crm-select2-row-content"><div class="crm-select2-row-label">' + row.label + '</div>';
+    markup += '<div class="crm-select2-row-description">' + (row.description || '') + '</div>';
+    markup += '</td></tr></table>';
+    return markup;
+  };
+
   // Initialize widgets
   $(document).on('crmLoad', function(e) {
     $('table.row-highlight', e.target)
@@ -291,39 +302,49 @@ CRM.validate = CRM.validate || {
       })
       .find('input.select-row:checked').parents('tr').addClass('crm-row-selected');
     $('.crm-select2', e.target).each(function() {
+      var $el = $(this);
       // quickform doesn't support optgroups so here's a hack :(
       $('option[value^=crm_optgroup]', this).each(function() {
         $(this).nextUntil('option[value^=crm_optgroup]').wrapAll('<optgroup label="' + $(this).text() + '" />');
         $(this).remove();
       });
-      var options = $(this).data('select-params') || {};
+      var options = $el.data('select-params') || {};
       // Set placeholder from markup if not specified
-      if ($(this).is('select:not([multiple])')) {
-        options.allowClear = options.allowClear !== undefined ? options.allowClear : !($(this).hasClass('required'));
+      if ($el.is('select:not([multiple])')) {
+        options.allowClear = options.allowClear !== undefined ? options.allowClear : !($el.hasClass('required'));
         if (options.placeHolder === undefined && $('option:first', this).val() === '') {
           options.placeholderOption = 'first';
         }
       }
       // Autocomplete using the getlist api
-      if ($(this).data('api-entity') && $(this).hasClass('crm-form-entityref')) {
-        $(this).addClass('crm-ajax-select')
-        options.query = function(info) {
-          var params = $(info.element).data('api-params') || {};
-          params.input = info.term;
-          params.page_num = info.page;
-          CRM.api3($(info.element).data('api-entity'), 'getlist', params).done(function(data) {
-            var results = {context: info.context, more: data.more_results, results: []};
-            if (typeof(data.values) === 'object') {
-              $.each(data.values, function(k, v) {
-                results.results.push({id: v.id, text: v.label});
-              });
+      if ($el.data('api-entity') && $el.hasClass('crm-form-entityref')) {
+        $el.addClass('crm-ajax-select');
+        $.extend(options, {
+          ajax: {
+            url: CRM.url('civicrm/ajax/rest'),
+            data: function (input, page_num) {
+              var params = $el.data('api-params') || {};
+              params.input = input;
+              params.page_num = page_num;
+              return {
+                entity: $el.data('api-entity'),
+                action: 'getlist',
+                json: JSON.stringify(params)
+              };
+            },
+            results: function(data) {
+              return {more: data.more_results, results: data.values || []};
             }
-            info.callback(results);
-          });
-        };
-        options.initSelection = function(el, callback) {
-          callback(el.data('entity-value'));
-        };
+          },
+          formatResult: CRM.utils.formatSelect2Result,
+          formatSelection: function(row) {
+            return row.label;
+          },
+          escapeMarkup: function (m) {return m;},
+          initSelection: function(el, callback) {
+            callback(el.data('entity-value'));
+          }
+        });
       }
       $(this).select2(options).removeClass('crm-select2');
     });
index aa4798a0e425165f38c809e6a835976b4755589a..33902c823e2c69771fa82bc30ff346209bd5e2d0 100644 (file)
@@ -198,6 +198,7 @@ class api_v3_TagTest extends CiviUnitTestCase {
       'input' => $this->tag['name'],
     );
     $result = $this->callAPIAndDocument('tag', 'getlist', $params, __FUNCTION__, __FILE__);
+    $this->assertEquals($this->tag['id'], $result['values'][0]['id'], 'In line ' . __LINE__);
     $this->assertEquals($this->tag['description'], $result['values'][0]['description'], 'In line ' . __LINE__);
   }
 }