Allow entityRef widget to create campaigns
authorColeman Watts <coleman@civicrm.org>
Tue, 22 Jan 2019 01:12:30 +0000 (20:12 -0500)
committerColeman Watts <coleman@civicrm.org>
Tue, 22 Jan 2019 01:12:30 +0000 (20:12 -0500)
CRM/Campaign/BAO/Campaign.php
CRM/Campaign/Form/Campaign.php
CRM/Contact/BAO/Contact.php
CRM/Contact/Form/Edit/Address.php
CRM/Core/BAO/UFGroup.php
CRM/Core/Form.php
api/v3/Campaign.php
js/Common.js

index a86e4e8966c783e50194938fd58efece75d34e60..356c84b09858d7465e5a81858eb8f4fd5e28a64d 100644 (file)
@@ -707,4 +707,22 @@ INNER JOIN  civicrm_group grp ON ( grp.id = campgrp.entity_id )
     $form->assign('campaignInfo', $campaignInfo);
   }
 
+  /**
+   * Links to create new campaigns from entityRef widget
+   *
+   * @return array|bool
+   */
+  public static function entityRefCreateLinks() {
+    if (CRM_Core_Permission::check([['administer CiviCampaign', 'manage campaign']])) {
+      return [
+        [
+          'label' => ts('New Campaign'),
+          'url' => CRM_Utils_System::url('civicrm/campaign/add', "reset=1",
+            NULL, NULL, FALSE, FALSE, TRUE),
+          'type' => 'Campaign',
+        ]];
+    }
+    return FALSE;
+  }
+
 }
index f94cb29a63f3f498a641c852a95e365606ce2376..865ad02b0fd434bf331078a82d73889ed9b75608 100644 (file)
@@ -244,23 +244,27 @@ class CRM_Campaign_Form_Campaign extends CRM_Core_Form {
     // is this Campaign active
     $this->addElement('checkbox', 'is_active', ts('Is Active?'));
 
-    $this->addButtons(array(
-        array(
-          'type' => 'upload',
-          'name' => ts('Save'),
-          'isDefault' => TRUE,
-        ),
-        array(
-          'type' => 'upload',
-          'name' => ts('Save and New'),
-          'subName' => 'new',
-        ),
-        array(
-          'type' => 'cancel',
-          'name' => ts('Cancel'),
-        ),
-      )
-    );
+    $buttons = [
+      [
+        'type' => 'upload',
+        'name' => ts('Save'),
+        'isDefault' => TRUE,
+      ],
+    ];
+    // Skip this button when adding a new campaign from an entityRef
+    if (empty($_GET['snippet']) || empty($_GET['returnExtra'])) {
+      $buttons[] = [
+        'type' => 'upload',
+        'name' => ts('Save and New'),
+        'subName' => 'new',
+      ];
+    }
+    $buttons[] = [
+      'type' => 'cancel',
+      'name' => ts('Cancel'),
+    ];
+
+    $this->addButtons($buttons);
   }
 
   /**
@@ -340,6 +344,8 @@ class CRM_Campaign_Form_Campaign extends CRM_Core_Form {
     if ($result) {
       CRM_Core_Session::setStatus(ts('Campaign %1 has been saved.', array(1 => $result->title)), ts('Saved'), 'success');
       $session->pushUserContext(CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=campaign'));
+      $this->ajaxResponse['id'] = $result->id;
+      $this->ajaxResponse['label'] = $result->title;
     }
 
     $buttonName = $this->controller->getButtonName();
index 4dbe7fd8b5c9280d78c9d1b7c4a2fbdcb34fa6f6..77761d4d18596508695bdbea789e1858a990d80e 100644 (file)
@@ -3642,4 +3642,16 @@ LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
     return FALSE;
   }
 
+  /**
+   * Checks permission to create new contacts from entityRef widget
+   *
+   * Note: other components must return an array of links from this function,
+   * but Contacts are given special treatment - the links are in javascript already.
+   *
+   * @return bool
+   */
+  public static function entityRefCreateLinks() {
+    return CRM_Core_Permission::check([['edit all contacts', 'add contacts']]);
+  }
+
 }
index 0e4399f033b7b6bcf39e163815b5e343fc0819da..1f80087afc5a21922bd7c1dfad77df72b9a06835 100644 (file)
@@ -165,11 +165,7 @@ class CRM_Contact_Form_Edit_Address {
       $form->addElement('checkbox', "address[$blockId][use_shared_address]", NULL, ts('Use another contact\'s address'));
 
       // Override the default profile links to add address form
-      $profileLinks = CRM_Core_BAO_UFGroup::getCreateLinks(array(
-          'new_individual',
-          'new_organization',
-          'new_household',
-        ), 'shared_address');
+      $profileLinks = CRM_Contact_BAO_Contact::entityRefCreateLinks() ? CRM_Core_BAO_UFGroup::getCreateLinks('', 'shared_address') : FALSE;
       $form->addEntityRef("address[$blockId][master_contact_id]", ts('Share With'), array('create' => $profileLinks));
     }
   }
index cf120a234fb1941c618a5dc7f64f924df32167b9..9fc2793259347a45af0fc40ac653c9310b64a391 100644 (file)
@@ -3340,6 +3340,11 @@ AND    ( entity_id IS NULL OR entity_id <= 0 )
     ));
     $links = $append = array();
     if (!empty($retrieved['values'])) {
+      $icons = [
+        'individual' => 'fa-user',
+        'organization' => 'fa-building',
+        'household' => 'fa-home',
+      ];
       foreach ($retrieved['values'] as $id => $profile) {
         if (in_array($profile['name'], $profiles)) {
           $links[] = array(
@@ -3347,6 +3352,7 @@ AND    ( entity_id IS NULL OR entity_id <= 0 )
             'url' => CRM_Utils_System::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
               NULL, NULL, FALSE, FALSE, TRUE),
             'type' => ucfirst(str_replace('new_', '', $profile['name'])),
+            'icon' => CRM_Utils_Array::value(str_replace('new_', '', $profile['name']), $icons),
           );
         }
         else {
index 8c0b84b291979dc41f2d5e3cd43a7809e056a37f..e8633e69d3157715301c07bffc0862c36b63dfa9 100644 (file)
@@ -1951,7 +1951,12 @@ class CRM_Core_Form extends HTML_QuickForm_Page {
     $props['entity'] = _civicrm_api_get_entity_name_from_camel(CRM_Utils_Array::value('entity', $props, 'contact'));
     $props['class'] = ltrim(CRM_Utils_Array::value('class', $props, '') . ' crm-form-entityref');
 
-    if ($props['entity'] == 'contact' && isset($props['create']) && !(CRM_Core_Permission::check('edit all contacts') || CRM_Core_Permission::check('add contacts'))) {
+    if (isset($props['create']) && $props['create'] === TRUE) {
+      require_once "api/v3/utils.php";
+      $baoClass = _civicrm_api3_get_BAO($props['entity']);
+      $props['create'] = $baoClass && is_callable([$baoClass, 'entityRefCreateLinks']) ? $baoClass::entityRefCreateLinks() : FALSE;
+    }
+    if (array_key_exists('create', $props) && empty($props['create'])) {
       unset($props['create']);
     }
 
index caea8f4d46c0317c9d2d2c7de09c03120ae0e0d0..bb1520358bce23c7779d1de3567a82b6b6c0eb98 100644 (file)
@@ -88,3 +88,56 @@ function civicrm_api3_campaign_get($params) {
 function civicrm_api3_campaign_delete($params) {
   return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
 }
+
+/**
+ * Get campaign list parameters.
+ *
+ * @see _civicrm_api3_generic_getlist_params
+ *
+ * @param array $request
+ */
+function _civicrm_api3_campaign_getlist_params(&$request) {
+  $fieldsToReturn = ['title', 'campaign_type_id', 'start_date', 'end_date'];
+  $request['params']['return'] = array_unique(array_merge($fieldsToReturn, $request['extra']));
+  if (empty($request['params']['id'])) {
+    $request['params'] += [
+      'is_active' => 1,
+    ];
+  }
+}
+
+/**
+ * Get campaign list output.
+ *
+ * @see _civicrm_api3_generic_getlist_output
+ *
+ * @param array $result
+ * @param array $request
+ *
+ * @return array
+ */
+function _civicrm_api3_campaign_getlist_output($result, $request) {
+  $output = [];
+  if (!empty($result['values'])) {
+    foreach ($result['values'] as $row) {
+      $data = [
+        'id' => $row[$request['id_field']],
+        'label' => $row[$request['label_field']],
+        'description' => [
+          CRM_Core_Pseudoconstant::getLabel(
+            'CRM_Campaign_BAO_Campaign',
+            'campaign_type_id',
+            $row['campaign_type_id']
+          ),
+        ],
+      ];
+      $config = CRM_Core_Config::singleton();
+      $data['description'][0] .= ': ' . CRM_Utils_Date::customFormat($row['start_date'], $config->dateformatFull) . ' - ';
+      if (!empty($row['end_date'])) {
+        $data['description'][0] .= CRM_Utils_Date::customFormat($row['end_date'], $config->dateformatFull);
+      }
+      $output[] = $data;
+    }
+  }
+  return $output;
+}
\ No newline at end of file
index 985e7d616ccb76c2b00e8e7ece334ce64aa42167..2bd7df6963e199df8d89d2833ebfa17d9c6211dd 100644 (file)
@@ -578,11 +578,13 @@ if (!CRM.vars) CRM.vars = {};
                 formUrl = $(this).attr('href') + '&returnExtra=display_name,sort_name' + (extra ? (',' + extra) : '');
               $el.select2('close');
               CRM.loadForm(formUrl, {
-                dialog: {width: 500, height: 220}
+                dialog: {width: '50%', height: 220}
               }).on('crmFormSuccess', function(e, data) {
                 if (data.status === 'success' && data.id) {
-                  data.label = data.extra.sort_name;
-                  CRM.status(ts('%1 Created', {1: data.extra.display_name}));
+                  if (!data.crmMessages) {
+                    CRM.status(ts('%1 Created', {1: data.label || data.extra.display_name}));
+                  }
+                  data.label = data.label || data.extra.sort_name;
                   if ($el.select2('container').hasClass('select2-container-multi')) {
                     var selection = $el.select2('data');
                     selection.push(data);
@@ -684,32 +686,16 @@ if (!CRM.vars) CRM.vars = {};
       createLinks = $el.data('create-links'),
       params = getEntityRefApiParams($el).params,
       markup = '<div class="crm-entityref-links">';
-    if (!createLinks || $el.data('api-entity').toLowerCase() !== 'contact') {
+    if (!createLinks || (createLinks === true && $el.data('api-entity').toLowerCase() !== 'contact')) {
       return '';
     }
     if (createLinks === true) {
       createLinks = params.contact_type ? _.where(CRM.config.entityRef.contactCreate, {type: params.contact_type}) : CRM.config.entityRef.contactCreate;
     }
     _.each(createLinks, function(link) {
-      var icon;
-      switch (link.type) {
-        case 'Individual':
-          icon = 'fa-user';
-          break;
-
-        case 'Organization':
-          icon = 'fa-building';
-          break;
-
-        case 'Household':
-          icon = 'fa-home';
-          break;
-      }
-      markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">';
-      if (icon) {
-        markup += '<i class="crm-i ' + icon + '"></i> ';
-      }
-      markup += _.escape(link.label) + '</a>';
+      markup += ' <a class="crm-add-entity crm-hover-button" href="' + link.url + '">' +
+        '<i class="crm-i ' + (link.icon || 'fa-plus-circle') + '"></i> ' +
+        _.escape(link.label) + '</a>';
     });
     markup += '</div>';
     return markup;