use latest DT approach
authorjitendrapurohit <jitendra.purohit@webaccessglobal.com>
Mon, 18 Jan 2016 13:19:56 +0000 (18:49 +0530)
committerjitendrapurohit <jitendra.purohit@webaccessglobal.com>
Mon, 18 Jan 2016 13:19:56 +0000 (18:49 +0530)
CRM/Core/BAO/CustomValueTable.php
CRM/Custom/Page/AJAX.php
CRM/Profile/Page/MultipleRecordFieldsListing.php
templates/CRM/Profile/Page/MultipleRecordFieldsListing.tpl

index 901abf8627ef909bd8a072e1fa49536919121dda..66ec5737483385cb2a18d9f2e785ee36c716b523 100644 (file)
@@ -400,13 +400,14 @@ class CRM_Core_BAO_CustomValueTable {
    *                                   is set the entityType is ignored
    *
    * @param bool $formatMultiRecordField
+   * @param array $DTparams - CRM-17810 dataTable params for the multiValued custom fields.
    *
    * @return array
    *   Array of custom values for the entity with key=>value
    *                                   pairs specified as civicrm_custom_field.id => custom value.
    *                                   Empty array if no custom values found.
    */
-  public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE) {
+  public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE, $DTparams = NULL) {
     if (!$entityID) {
       // adding this here since an empty contact id could have serious repurcussions
       // like looping forever
@@ -429,6 +430,16 @@ class CRM_Core_BAO_CustomValueTable {
     }
     $cond = implode(' AND ', $cond);
 
+    $limit = '';
+    if (!empty($DTparams['rowCount']) && $DTparams['rowCount'] > 0) {
+      $limit = " LIMIT {$DTparams['offset']}, {$DTparams['rowCount']} ";
+    }
+
+    $orderBy = '';
+    if (!empty($DTparams['sort'])) {
+      $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($DTparams['sort'], 'String');
+    }
+
     // First find all the fields that extend this type of entity.
     $query = "
 SELECT cg.table_name,
@@ -461,8 +472,9 @@ AND    $cond
 
     $result = array();
     foreach ($select as $tableName => $clauses) {
-      $query = "SELECT id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID";
+      $query = "SELECT SQL_CALC_FOUND_ROWS id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID {$orderBy} {$limit}";
       $dao = CRM_Core_DAO::executeQuery($query);
+      $result['count'] = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()');
       while ($dao->fetch()) {
         foreach ($fields[$tableName] as $fieldID) {
           $fieldName = "custom_{$fieldID}";
index 9f941b4c38e0b369e62dc20012d16bc6da1d7a4d..65685deac0d48c6b663b71a24635ef7b8d11a3ac 100644 (file)
@@ -110,11 +110,16 @@ class CRM_Custom_Page_AJAX {
    *
    */
   public static function getMultiRecordFieldList() {
-    $params = $_REQUEST;
+    $params = $_GET;
 
-    $sEcho = CRM_Utils_Type::escape($_GET['sEcho'], 'Integer');
-    $offset = isset($params['iDisplayStart']) ? CRM_Utils_Type::escape($params['iDisplayStart'], 'Integer') : 0;
-    $rowCount = isset($params['iDisplayLength']) ? CRM_Utils_Type::escape($params['iDisplayLength'], 'Integer') : 25;
+    $offset = isset($_GET['start']) ? CRM_Utils_Type::escape($_GET['start'], 'Integer') : 0;
+    $rowCount = isset($_GET['length']) ? CRM_Utils_Type::escape($_GET['length'], 'Integer') : 10;
+    $sortMapper = array();
+    foreach ($_GET['columns'] as $key => $value) {
+      $sortMapper[$key] = $value['data'];
+    };
+    $sort = isset($_GET['order'][0]['column']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_GET['order'][0]['column'], 'Integer'), $sortMapper) : NULL;
+    $sortOrder = isset($_GET['order'][0]['dir']) ? CRM_Utils_Type::escape($_GET['order'][0]['dir'], 'String') : 'asc';
 
     $params['page'] = ($offset / $rowCount) + 1;
     $params['rp'] = $rowCount;
@@ -125,34 +130,36 @@ class CRM_Custom_Page_AJAX {
     $obj->_contactId = $params['cid'];
     $obj->_customGroupId = $params['cgid'];
     $obj->_contactType = $contactType;
-    $obj->_offset = ($params['page'] - 1) * $params['rp'];
-    $obj->_rowCount = $params['rp'];
+    $obj->_DTparams['offset'] = ($params['page'] - 1) * $params['rp'];
+    $obj->_DTparams['rowCount'] = $params['rp'];
+    if ($sort && $sortOrder) {
+      $sort = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $sort, 'column_name', 'label');
+      $obj->_DTparams['sort'] = $sort . ' ' . $sortOrder;
+    }
 
-    list($headers, $multiRecordFields) = $obj->browse();
+    list($fields, $attributes) = $obj->browse();
 
-    // sort the fields by the columns
-    $sortMapper = array_values($headers);
-    $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
-    $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
-    if ($sort && $sortOrder) {
-      $sortOrder = constant('SORT_' . strtoupper($sortOrder));
-      $sortCol = array();
-      $dataType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $sort, 'data_type');
-      foreach ($multiRecordFields as $key => $row) {
-        $sortCol[$key] = $row[$sort];
-        if ($dataType == 'Date') {
-          $sortCol[$key] = CRM_Utils_Date::unixTime($row[$sort]);
+    // format params and add links
+    $fieldList = array();
+    foreach ($fields as $id => $value) {
+      $field = array();
+      foreach ($value as $fieldId => $fieldName) {
+        if (is_numeric($fieldId)) {
+          $fieldName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $fieldId, 'label');
+          CRM_Utils_Array::crmReplaceKey($value, $fieldId, $fieldName);
         }
       }
-      array_multisort($sortCol, $sortOrder, $multiRecordFields);
+      $field = $value;
+      array_push($fieldList, $field);
     }
+    $fieldList = array_map('array_merge', $fieldList);
 
-    $iFilteredTotal = $iTotal = $obj->_total;
-    $selectorElements = array_merge($headers, array('action', 'class'));
+    $multiRecordFields = array();
+    $multiRecordFields['data'] = $fieldList;
+    $multiRecordFields['recordsTotal'] = $obj->_total;
+    $multiRecordFields['recordsFiltered'] = $obj->_total;
 
-    CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
-    echo CRM_Utils_JSON::encodeDataTableSelector($multiRecordFields, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($multiRecordFields);
   }
 
 }
index 9ee81ca02c5b0ae5b6f35a7f1118d0f629290e95..b5b8db6138458ace520ac167008cd0af74e38958 100644 (file)
@@ -171,7 +171,7 @@ class CRM_Profile_Page_MultipleRecordFieldsListing extends CRM_Core_Page_Basic {
   public function browse() {
     $dateFields = NULL;
     $cgcount = 0;
-    $attributes = array();
+    $attributes = $headerAttr = array();
     $dateFieldsVals = NULL;
     if ($this->_pageViewType == 'profileDataView' && $this->_profileId) {
       $fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, NULL,
@@ -260,8 +260,11 @@ class CRM_Profile_Page_MultipleRecordFieldsListing extends CRM_Core_Page_Basic {
         $options[$fieldIDs[$key]]['attributes']['time_format'] = CRM_Utils_Array::value('time_format', $returnValues);
       }
 
+      $DTparams = !empty($this->_DTparams) ? $this->_DTparams : NULL;
       // commonly used for both views i.e profile listing view (profileDataView) and custom data listing view (customDataView)
-      $result = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_contactId, NULL, $fieldIDs, TRUE);
+      $result = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_contactId, NULL, $fieldIDs, TRUE, $DTparams);
+      $resultCount = $result['count'];
+      unset($result['count']);
 
       if ($this->_pageViewType == 'profileDataView') {
         if (!empty($fieldIDs)) {
@@ -298,11 +301,10 @@ class CRM_Profile_Page_MultipleRecordFieldsListing extends CRM_Core_Page_Basic {
         if ($reached) {
           unset($links[CRM_Core_Action::COPY]);
         }
-        $newCgCount = (!$reached) ? count($result) + 1 : NULL;
-        if (isset($this->_offset) && isset($this->_rowCount)) {
-          $this->_total = count($result);
-          $result = array_slice($result, $this->_offset, $this->_rowCount, TRUE);
-          $cgcount = $this->_offset + 1;
+        $newCgCount = (!$reached) ? $resultCount + 1 : NULL;
+        if (!empty($DTparams)) {
+          $this->_total = $resultCount;
+          $cgcount = $DTparams['offset'] + 1;
         }
         foreach ($result as $recId => &$value) {
           foreach ($value as $fieldId => &$val) {
@@ -367,6 +369,7 @@ class CRM_Profile_Page_MultipleRecordFieldsListing extends CRM_Core_Page_Basic {
               }
               if ($editable) {
                 $fieldAttributes['class'] .= ' crm-editable';
+                $headerAttr[$fieldId]['class'] = 'crm-editable';
               }
               $attributes[$fieldId][$recId] = $fieldAttributes;
 
@@ -380,6 +383,8 @@ class CRM_Profile_Page_MultipleRecordFieldsListing extends CRM_Core_Page_Basic {
                 $op = 'profile.multiValue.row';
               }
               else {
+                $headerAttr[$fieldId]['dataType'] = CRM_Utils_Array::value('data-type', $fieldAttributes);
+                $headerAttr[$fieldId]['dataEmptyOption'] = CRM_Utils_Array::value('data-empty-option', $fieldAttributes);
                 // different set of url params
                 $actionParams['gid'] = $actionParams['groupID'] = $this->_customGroupId;
                 $actionParams['cid'] = $actionParams['entityID'] = $this->_contactId;
@@ -403,7 +408,7 @@ class CRM_Profile_Page_MultipleRecordFieldsListing extends CRM_Core_Page_Basic {
                 $actionParams['cs'] = $pageCheckSum;
               }
 
-              $value['action'] = CRM_Core_Action::formLink(
+              $value['links'] = CRM_Core_Action::formLink(
                 $links,
                 $linkAction,
                 $actionParams,
@@ -423,7 +428,7 @@ class CRM_Profile_Page_MultipleRecordFieldsListing extends CRM_Core_Page_Basic {
     $headers = array();
     if (!empty($fieldIDs)) {
       foreach ($fieldIDs as $fieldID) {
-        $headers[$fieldID] = ($this->_pageViewType == 'profileDataView') ? $customGroupInfo[$fieldID]['fieldLabel'] : !isset($this->_offset) ? $fieldLabels[$fieldID]['label'] : $fieldID;
+        $headers[$fieldID] = ($this->_pageViewType == 'profileDataView') ? $customGroupInfo[$fieldID]['fieldLabel'] : $fieldLabels[$fieldID]['label'];
       }
     }
     $this->assign('dateFields', $dateFields);
@@ -433,10 +438,11 @@ class CRM_Profile_Page_MultipleRecordFieldsListing extends CRM_Core_Page_Basic {
     $this->assign('contactType', $this->_contactType);
     $this->assign('customGroupTitle', $this->_customGroupTitle);
     $this->assign('headers', $headers);
+    $this->assign('headerAttr', $headerAttr);
     $this->assign('records', $result);
-    $this->assign('attributes', json_encode($attributes));
+    $this->assign('attributes', $attributes);
 
-    return array($headers, $result);
+    return array($result, $attributes);
   }
 
   /**
index e7fa21028a76a6dd0aecb3d9a36c31fa530b5d90..d6870cd4323abd85feb211a126c7e93780e7b4cf 100644 (file)
     <div id="custom-{$customGroupId}-table-wrapper" {if $pageViewType eq 'customDataView'}class="crm-entity" data-entity="contact" data-id="{$contactId}"{/if}>
       <div>
         {strip}
-          <table id="records" class={if $pageViewType eq 'customDataView'}"crm-multifield-selector"{else}'display'{/if}>
+          <table id="records" class={if $pageViewType eq 'customDataView'}"crm-multifield-selector crm-ajax-table"{else}'display'{/if}>
             <thead>
             <tr>
+            {if $pageViewType eq 'customDataView'}
               {foreach from=$headers key=recId item=head}
-                <th>{ts}{$head}{/ts}</th>
-              {/foreach}
-              <th></th>
-              {foreach from=$dateFields key=fieldId item=v}
-                <th class='hiddenElement'></th>
+                <th data-data={ts}'{$head}'{/ts} cell-class="{$headerAttr.$recId.class}"
+                {if !empty($headerAttr.$recId.dataType)}cell-data-type="{$headerAttr.$recId.dataType}"{/if}
+                {if !empty($headerAttr.$recId.dataEmptyOption)}cell-data-empty-option="{$headerAttr.$recId.dataEmptyOption}"{/if}>{ts}{$head}{/ts}
+                </th>
               {/foreach}
+              <th data-data="links" data-orderable="false">&nbsp;</th>
             </tr>
             </thead>
-            {if $pageViewType eq 'customDataView'}
               {literal}
               <script type="text/javascript">
-              CRM.$(function($) {
-                var sourceUrl = {/literal}'{crmURL p="civicrm/ajax/multirecordfieldlist" h=0 q="snippet=4&cid=$contactId&cgid=$customGroupId"}'{literal};
-
-                $('table.crm-multifield-selector').dataTable({
-                  "bProcessing": true,
-                  "aaSorting": [],
-                  "asStripClasses" : [ "odd-row", "even-row" ],
-                  "sPaginationType": "full_numbers",
-                  "sDom"       : '<"crm-datatable-pager-top"lfp>rt<"crm-datatable-pager-bottom"ip>',
-                  "bServerSide": true,
-                  "sAjaxSource": sourceUrl,
-                });
-
-                $(".crm-multifield-selector").on('click','.delete-custom-row', function (e) {
+                (function($) {
+                  $('table.crm-multifield-selector').data({
+                    "ajax": {
+                      "url": {/literal}'{crmURL p="civicrm/ajax/multirecordfieldlist" h=0 q="snippet=4&cid=$contactId&cgid=$customGroupId"}'{literal},
+                    },
+                    "aaSorting": [],
+                    "pageLength": 10,
+                  })
+                  $(".crm-multifield-selector").on('click','.delete-custom-row', function (e) {
                   var $el = $(this);
                   CRM.confirm({
                     message: '{/literal}{ts escape='js'}Are you sure you want to delete this record?{/ts}{literal}'
                   }).on('crmConfirm:yes', function() {
-                    var postUrl = {/literal}"{crmURL p='civicrm/ajax/customvalue' h=0 }"{literal};
-                    var request = $.post(postUrl, $el.data('delete_params'));
-                    CRM.status({/literal}"{ts escape='js'}Record Deleted{/ts}"{literal}, request);
-                    request.done(function() {
-                      CRM.refreshParent($el);
-                    });
-                  })
-                  e.preventDefault();
-                });
-              });
+                      var postUrl = {/literal}"{crmURL p='civicrm/ajax/customvalue' h=0 }"{literal};
+                      var request = $.post(postUrl, $el.data('delete_params'));
+                      CRM.status({/literal}"{ts escape='js'}Record Deleted{/ts}"{literal}, request);
+                      request.done(function() {
+                        CRM.refreshParent($el);
+                      });
+                    })
+                    e.preventDefault();
+                  });
+                })(CRM.$);
               </script>
               {/literal}
+
             {else}
+              {foreach from=$headers key=recId item=head}
+                <th>{ts}{$head}{/ts}</th>
+              {/foreach}
+              <th></th>
+              {foreach from=$dateFields key=fieldId item=v}
+                <th class='hiddenElement'></th>
+              {/foreach}
+              <th>&nbsp;</th>
+              </tr>
+              </thead>
               {foreach from=$records key=recId item=rows}
                 <tr class="{cycle values="odd-row,even-row"}">
                   {foreach from=$headers key=hrecId item=head}