CRM-13966 - Add ajax save support for new tagSet code
authorColeman Watts <coleman@civicrm.org>
Wed, 30 Apr 2014 06:42:55 +0000 (23:42 -0700)
committerColeman Watts <coleman@civicrm.org>
Wed, 30 Apr 2014 06:42:55 +0000 (23:42 -0700)
CRM/Core/Form/Tag.php
CRM/Tag/Form/Tag.php
js/Common.js
js/crm.ajax.js
templates/CRM/Tag/Form/Tag.tpl
templates/CRM/common/Tagset.tpl

index 05adaefbe5daad4912cc59fe849351b1c7124651..52399b78b68ef5c2fa9c383e8fcfd11c1207926d 100644 (file)
@@ -44,7 +44,7 @@ class CRM_Core_Form_Tag {
    * Function to build tag widget if correct parent is passed
    *
    * @param CRM_Core_Form  $form form object
-   * @param string  $parentName parent name ( tag name)
+   * @param string  $parentNames parent name ( tag name)
    * @param string  $entityTable entitytable 'eg: civicrm_contact'
    * @param int     $entityId    entityid  'eg: contact id'
    * @param boolean $skipTagCreate true if tag need be created using ajax
@@ -67,25 +67,15 @@ class CRM_Core_Form_Tag {
       $parentId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $parentNameItem, 'id', 'name');
 
       // check if parent exists
-      $entityTags = array();
       if ($parentId) {
         $tagsetItem = 'parentId_' . $parentId;
-        $tagset[$tagsetItem]['parentName'] = $parentNameItem;
+        $tagset[$tagsetItem]['skipEntityAction'] = $skipEntityAction;
         $tagset[$tagsetItem]['parentID'] = $parentId;
 
-        //tokeninput url
-        $qparams = "parentId={$parentId}";
-
-        if ($searchMode) {
-          $qparams .= '&search=1';
-        }
-
-        $tagUrl = CRM_Utils_System::url('civicrm/ajax/taglist', $qparams, FALSE, NULL, FALSE);
-
-        $tagset[$tagsetItem]['tagUrl'] = $tagUrl;
+        // Fixme: these 3 variables may be unused
+        $tagset[$tagsetItem]['parentName'] = $parentNameItem;
         $tagset[$tagsetItem]['entityTable'] = $entityTable;
         $tagset[$tagsetItem]['skipTagCreate'] = $skipTagCreate;
-        $tagset[$tagsetItem]['skipEntityAction'] = $skipEntityAction;
 
         switch ($entityTable) {
           case 'civicrm_activity':
@@ -109,117 +99,26 @@ class CRM_Core_Form_Tag {
 
         $tagset[$tagsetItem]['tagsetElementName'] = $tagsetElementName;
         if ($tagsetElementName) {
-          $form->addEntityRef("{$tagsetElementName}[{$parentId}]", NULL, array(
+          $form->addEntityRef("{$tagsetElementName}[{$parentId}]", $parentNameItem, array(
             'entity' => 'tag',
             'multiple' => TRUE,
-            'create' => TRUE,
-            'api' => array('params' => array('parent_id' => $parentId)))
-          );
+            'create' => !$skipTagCreate,
+            'api' => array('params' => array('parent_id' => $parentId)),
+            'data-entity_table' => $entityTable,
+            'data-entity_id' => $entityId,
+            'class' => "crm-$mode-tagset",
+          ));
         }
 
         if ($entityId) {
           $tagset[$tagsetItem]['entityId'] = $entityId;
           $entityTags = CRM_Core_BAO_EntityTag::getChildEntityTags($parentId, $entityId, $entityTable);
-        }
-        else {
-
-          switch ($entityTable) {
-            case 'civicrm_activity':
-              if (!empty($form->_submitValues['activity_taglist']) && !empty($form->_submitValues['activity_taglist'][$parentId])) {
-                $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
-                $tagIds = explode(',', $form->_submitValues['activity_taglist'][$parentId]);
-                foreach ($tagIds as $tagId) {
-                  if (is_numeric($tagId)) {
-                    $tagName = $allTags[$tagId];
-                  }
-                  else {
-                    $tagName = $tagId;
-                  }
-                  $entityTags[$tagId] = array(
-                    'id' => $tagId,
-                    'name' => $tagName,
-                  );
-                }
-              }
-              break;
-
-            case 'civicrm_case':
-              if (!empty($form->_submitValues['case_taglist']) && !empty($form->_submitValues['case_taglist'][$parentId])) {
-                $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
-                $tagIds = explode(',', $form->_submitValues['case_taglist'][$parentId]);
-                foreach ($tagIds as $tagId) {
-                  if (is_numeric($tagId)) {
-                    $tagName = $allTags[$tagId];
-                  }
-                  else {
-                    $tagName = $tagId;
-                  }
-                  $entityTags[$tagId] = array(
-                    'id' => $tagId,
-                    'name' => $tagName,
-                  );
-                }
-              }
-              break;
-            case 'civicrm_file':
-              $numAttachments = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'max_attachments');
-              for ($i = 1; $i <= $numAttachments; $i++) {
-                $tagset[$i] = $tagset[$tagsetItem];
-                $tagset[$i]['tagsetElementName'] = "attachment_taglist_$i";
-                $form->add('text', "attachment_taglist_{$i}[{$parentId}]", NULL);
-                if (!empty($form->_submitValues["attachment_taglist_$i"]) && !empty($form->_submitValues["attachment_taglist_$i"][$parentId])) {
-                  $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
-                  $tagIds = explode(',', $form->_submitValues["attachment_taglist_$i"][$parentId]);
-                  foreach ($tagIds as $tagId) {
-                    if (is_numeric($tagId)) {
-                      $tagName = $allTags[$tagId];
-                    }
-                    else {
-                      $tagName = $tagId;
-                    }
-                    $entityTags[$tagId] = array(
-                      'id' => $tagId,
-                      'name' => $tagName,
-                    );
-                  }
-                }
-              }
-              unset($tagset[$tagsetItem]);
-              break;
-
-            default:
-              if (!empty($form->_formValues['contact_tags'])) {
-                $contactTags = CRM_Core_BAO_Tag::getTagsUsedFor('civicrm_contact', TRUE, FALSE, $parentId);
-
-                foreach (array_keys($form->_formValues['contact_tags']) as $tagId) {
-                  if (!empty($contactTags[$tagId])) {
-                    $tagName = $tagId;
-                    if (is_numeric($tagId)) {
-                      $tagName = $contactTags[$tagId];
-                    }
-
-                    $entityTags[$tagId] = array(
-                      'id' => $tagId,
-                      'name' => $tagName,
-                    );
-                  }
-                }
-              }
+          if ($entityTags) {
+            $form->setDefaults(array("{$tagsetElementName}[{$parentId}]" => implode(',', array_keys($entityTags))));
           }
         }
-
-        if (!empty($entityTags)) {
-          // assign as simple array for display in smarty
-          $tagset[$tagsetItem]['entityTagsArray'] = $entityTags;
-          // assign as json for js widget
-          $tagset[$tagsetItem]['entityTags'] = json_encode(array_values($entityTags));
-
-          if (!empty($form->_entityTagValues)) {
-            $form->_entityTagValues = CRM_Utils_Array::crmArrayMerge($entityTags, $form->_entityTagValues);
-          }
-          else {
-            $form->_entityTagValues = $entityTags;
-          }
+        else {
+          $skipEntityAction = TRUE;
         }
       }
     }
index 5492a05e51cf9468c2527913d543d61af0300748..2b2a97ae63d28b0bafcbcb6bf62ccbac238fe63b 100644 (file)
@@ -112,7 +112,7 @@ class CRM_Tag_Form_Tag extends CRM_Core_Form {
     CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, $this->_entityTable, $this->_entityID);
 
     if ($this->_action & CRM_Core_Action::BROWSE) {
-      $this->freeze();
+      //$this->freeze();
     }
     else {
       $this->addButtons(array(
index ae938704ed0472996e2fed76923c82594ff992d6..42d4cafd69b608038ab4b7a888e84e2ee0415ffa 100644 (file)
@@ -368,7 +368,7 @@ CRM.validate = CRM.validate || {
             return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
           }
         };
-        selectParams.tokenSeparators = [',', ' '];
+        selectParams.tokenSeparators = [','];
         selectParams.createSearchChoicePosition = 'bottom';
       }
       $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams))
@@ -383,12 +383,12 @@ CRM.validate = CRM.validate || {
                   data = $el.select2('data'),
                   item = {id: created.id, label: e.object.term};
                 if (val === "0") {
-                  $el.select2('data', item);
+                  $el.select2('data', item, true);
                 }
                 else if ($.isArray(val) && $.inArray("0", val) > -1) {
                   _.remove(data, {id: "0"});
                   data.push(item);
-                  $el.select2('data', data);
+                  $el.select2('data', data, true);
                 }
               });
           }
index 066269b15a2b3208bd6e9441434461b3b670b64f..78205449cfc85b96b79009bf22a4ccaaacc66897 100644 (file)
@@ -71,7 +71,8 @@
         entity: 'api3',
         action: 'call',
         json: JSON.stringify(entity)
-      }
+      };
+      status = action;
     }
     var ajax = $.ajax({
       url: CRM.url('civicrm/ajax/rest'),
index 94f5750e826e1ce4ca670d2fcdd50844237829d2..9da84a2604b1e8192b6b2954904ebffec019fed9 100644 (file)
   }
 </style>
 <script type="text/javascript">
-  (function($){{/literal}
+  (function($, _){{/literal}
     var entityID={$entityID};
     var entityTable='{$entityTable}';
     {literal}
+    CRM.updateContactSummaryTags = function() {
+      var tags = [];
+      $('#tagtree input:checkbox:checked+label').each(function() {
+        tags.push($(this).text());
+      });
+      $('input.crm-contact-tagset').each(function() {
+        var setTags = _.pluck($(this).select2('data'), 'label');
+        tags = tags.concat(setTags);
+      });
+      // contact summary tabs and search forms both listen for this event
+      $('#Tag').closest('.crm-ajax-container').trigger('crmFormSuccess', {tabCount: tags.length});
+      // update summary tab
+      $("#contact-summary #tags").html(tags.join(', '));
+    };
+
     $(function() {
       $("#tagtree ul input:checked").each (function(){
         $(this).closest("li").addClass('highlighted');
         {/literal}
       {/if}
       {literal}
-    });
 
-    CRM.updateContactSummaryTags = function() {
-      var tags = [];
-      $('.tag-section .token-input-token-facebook p, #tagtree input:checkbox:checked+label').each(function() {
-        tags.push($(this).text());
-      });
-      // contact summary tabs and search forms both listen for this event
-      $('#Tag').closest('.crm-ajax-container').trigger('crmFormSuccess', {tabCount: tags.length});
-      // update summary tab
-      $("#contact-summary #tags").html(tags.join(', '));
-    };
-  })(CRM.$);
+      $(document).on('change', 'input.crm-contact-tagset', CRM.updateContactSummaryTags);
+    });
+  })(CRM.$, CRM._);
   {/literal}
 </script>
 <div id="Tag" class="view-content">
index 8d19c9a2b35ae7511df0726c7c5d0db499d0fddd..8d877b8643c2c1e2a0588ca0567b46e3f69a6e31 100644 (file)
  +--------------------------------------------------------------------+
 *}
 {if empty($tagsetType)}
-  {capture assign="tagsetType"}contact{/capture}
+  {assign var="tagsetType" value="contact"}contact{/capture}
 {/if}
 {foreach from=$tagsetInfo.$tagsetType item=tagset}
   <div class="crm-section tag-section {$tagsetType}-tagset {$tagsetType}-tagset-{$tagset.parentID}-section">
-    <label>{$tagset.parentName}</label>
     <div class="crm-clearfix"{if $context EQ "contactTab"} style="margin-top:-15px;"{/if}>
-      {assign var=elemName  value = $tagset.tagsetElementName}
-      {assign var=parID     value = $tagset.parentID}
-      {assign var=editTagSet value=false}
+      {assign var="elemName" value=$tagset.tagsetElementName}
+      {assign var="parID" value=$tagset.parentID}
+      {$form.$elemName.$parID.label}
       {$form.$elemName.$parID.html}
-      {if $action ne 4 }
-        {assign var=editTagSet value=true}
-        {if $action eq 16 and !($permission eq 'edit') }
-          {assign var=editTagSet value=false}
-        {/if}
-      {/if}
     </div>
+    {if !$tagset.skipEntityAction}
+      <script type="text/javascript">
+        {* Add/remove entity tags via ajax api *}
+        {literal}
+        (function($, _) {
+          var $el = $('.{/literal}{$tagsetType}-tagset-{$tagset.parentID}-section{literal} input.crm-form-entityref');
+          // select2 provides "added" and "removed" properties in the event
+          $el.on('change', function(e) {
+            var tags,
+              data = _.pick($(this).data(), 'entity_id', 'entity_table'),
+              apiCall = [];
+            if (e.added) {
+              tags = $.isArray(e.added) ? e.added : [e.added];
+              _.each(tags, function(tag) {
+                if (tag.id && tag.id != '0') {
+                  apiCall.push(['entity_tag', 'create', $.extend({tag_id: tag.id}, data)]);
+                }
+              });
+            }
+            if (e.removed) {
+              tags = $.isArray(e.removed) ? e.removed : [e.removed];
+              _.each(tags, function(tag) {
+                if (tag.id && tag.id != '0') {
+                  apiCall.push(['entity_tag', 'delete', $.extend({tag_id: tag.id}, data)]);
+                }
+              });
+            }
+            if (apiCall.length) {
+              CRM.api3(apiCall, true);
+            }
+          });
+        }(CRM.$, CRM._));
+        {/literal}
+      </script>
+    {/if}
   </div>
 {/foreach}