optimization
[civicrm-core.git] / CRM / Core / BAO / CustomField.php
index ff0fe52032a70acd20134527747c9ae154e19f83..ae9c4023a18b806875c4058d6ceb543267825567 100644 (file)
@@ -57,11 +57,6 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
    */
   public static $_importFields = NULL;
 
-  /**
-   * @var array
-   */
-  public static $displayInfoCache = array();
-
   /**
    * Build and retrieve the list of data types and descriptions.
    *
@@ -401,12 +396,10 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
       $options = $context == 'validate' ? array(0, 1) : CRM_Core_SelectValues::boolean();
     }
     else {
-      return false;
+      return FALSE;
     }
     CRM_Utils_Hook::customFieldOptions($this->id, $options, FALSE);
-    $entity = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id, 'extends');
-    $entity = in_array($entity, array('Individual', 'Household', 'Organization')) ? 'Contact' : $entity;
-    CRM_Utils_Hook::fieldOptions($entity, "custom_{$this->id}", $options, array('context' => $context));
+    CRM_Utils_Hook::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, array('context' => $context));
     return $options;
   }
 
@@ -748,11 +741,11 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
    * @param int $fieldID
    *   The custom field ID.
    *
-   * @return CRM_Core_DAO_CustomField
+   * @return CRM_Core_BAO_CustomField
    *   The field object.
    */
   public static function getFieldObject($fieldID) {
-    $field = new CRM_Core_DAO_CustomField();
+    $field = new CRM_Core_BAO_CustomField();
 
     // check if we can get the field values from the system cache
     $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
@@ -777,33 +770,28 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
   }
 
   /**
-   * This function for building custom fields.
+   * Add a custom field to an existing form.
    *
    * @param CRM_Core_Form $qf
    *   Form object (reference).
    * @param string $elementName
    *   Name of the custom field.
    * @param int $fieldId
-   * @param bool $inactiveNeeded
-   *   -deprecated.
    * @param bool $useRequired
    *   True if required else false.
    * @param bool $search
    *   True if used for search else false.
    * @param string $label
    *   Label for custom field.
+   * @return \HTML_QuickForm_Element|null
+   * @throws \CiviCRM_API3_Exception
    */
   public static function addQuickFormElement(
-    &$qf,
-    $elementName,
-    $fieldId,
-    $inactiveNeeded = FALSE,
-    $useRequired = TRUE,
-    $search = FALSE,
-    $label = NULL
+    $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
   ) {
     $field = self::getFieldObject($fieldId);
     $widget = $field->html_type;
+    $element = NULL;
 
     // Custom field HTML should indicate group+field name
     $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id);
@@ -832,10 +820,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
     )));
 
     if ($isSelect) {
-      $options = CRM_Utils_Array::value('values', civicrm_api3('contact', 'getoptions', array(
-        'field' => "custom_$fieldId",
-        'context' => $search ? 'search' : 'create',
-      ), array()));
+      $options = $field->getOptions($search ? 'search' : 'create');
 
       // Consolidate widget types to simplify the below switch statement
       if ($search || ($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
@@ -854,8 +839,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
       // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
       if ($field->option_group_id && !$search && $widget == 'Select' && CRM_Core_Permission::check('administer CiviCRM')) {
         $selectAttributes += array(
-          'data-api-entity' => 'contact',
-          // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
+          'data-api-entity' => $field->getEntity(),
           'data-api-field' => 'custom_' . $field->id,
           'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id),
         );
@@ -876,7 +860,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
           $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
         }
         else {
-          $element = &$qf->add('text', $elementName, $label,
+          $element = $qf->add('text', $elementName, $label,
             $field->attributes,
             $useRequired && !$search
           );
@@ -900,7 +884,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
         if ($field->text_length) {
           $attributes .= ' maxlength=' . $field->text_length;
         }
-        $element = &$qf->add('textarea',
+        $element = $qf->add('textarea',
           $elementName,
           $label,
           $attributes,
@@ -909,37 +893,19 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
         break;
 
       case 'Select Date':
+        $attr = array('data-crm-custom' => $dataCrmCustomVal);
+        $params = array(
+          'date' => $field->date_format,
+          'minDate' => isset($field->start_date_years) ? (date('Y') - $field->start_date_years) . '-01-01' : NULL,
+          'maxDate' => isset($field->end_date_years) ? (date('Y') + $field->end_date_years) . '-01-01' : NULL,
+          'time' => $field->time_format ? $field->time_format * 12 : FALSE,
+        );
         if ($field->is_search_range && $search) {
-          $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
-            array(
-              'format' => $field->date_format,
-              'timeFormat' => $field->time_format,
-              'startOffset' => $field->start_date_years,
-              'endOffset' => $field->end_date_years,
-              'data-crm-custom' => $dataCrmCustomVal,
-            )
-          );
-
-          $qf->addDate($elementName . '_to', ts('To'), FALSE,
-            array(
-              'format' => $field->date_format,
-              'timeFormat' => $field->time_format,
-              'startOffset' => $field->start_date_years,
-              'endOffset' => $field->end_date_years,
-              'data-crm-custom' => $dataCrmCustomVal,
-            )
-          );
+          $qf->add('datepicker', $elementName . '_from', $label, $attr + array('placeholder' => ts('From')), FALSE, $params);
+          $qf->add('datepicker', $elementName . '_to', NULL, $attr + array('placeholder' => ts('To')), FALSE, $params);
         }
         else {
-          $required = $useRequired && !$search;
-
-          $qf->addDate($elementName, $label, $required, array(
-            'format' => $field->date_format,
-            'timeFormat' => $field->time_format,
-            'startOffset' => $field->start_date_years,
-            'endOffset' => $field->end_date_years,
-            'data-crm-custom' => $dataCrmCustomVal,
-          ));
+          $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
         }
         break;
 
@@ -948,12 +914,12 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
         foreach ($options as $v => $l) {
           $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes);
         }
-        $group = $qf->addGroup($choice, $elementName, $label);
+        $element = $qf->addGroup($choice, $elementName, $label);
         if ($useRequired && !$search) {
           $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
         }
         else {
-          $group->setAttribute('allowClear', TRUE);
+          $element->setAttribute('allowClear', TRUE);
         }
         break;
 
@@ -962,7 +928,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
         if (empty($selectAttributes['multiple'])) {
           $options = array('' => $placeholder) + $options;
         }
-        $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
+        $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
 
         // Add and/or option for fields that store multiple values
         if ($search && self::isSerialized($field)) {
@@ -977,7 +943,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
         break;
 
       case 'AdvMulti-Select':
-        $include =& $qf->addElement(
+        $element = $qf->addElement(
           'advmultiselect',
           $elementName,
           $label, $options,
@@ -989,8 +955,8 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
           )
         );
 
-        $include->setButtonAttributes('add', array('value' => ts('Add >>')));
-        $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
+        $element->setButtonAttributes('add', array('value' => ts('Add >>')));
+        $element->setButtonAttributes('remove', array('value' => ts('<< Remove')));
 
         if ($useRequired && !$search) {
           $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
@@ -1002,7 +968,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
         foreach ($options as $v => $l) {
           $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
         }
-        $qf->addGroup($check, $elementName, $label);
+        $element = $qf->addGroup($check, $elementName, $label);
         if ($useRequired && !$search) {
           $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
         }
@@ -1011,9 +977,9 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
       case 'File':
         // we should not build upload file in search mode
         if ($search) {
-          return;
+          return NULL;
         }
-        $qf->add(
+        $element = $qf->add(
           strtolower($field->html_type),
           $elementName,
           $label,
@@ -1032,7 +998,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
         if ($field->text_length) {
           $attributes['maxlength'] = $field->text_length;
         }
-        $qf->add('wysiwyg', $elementName, $label, $attributes, $search);
+        $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $search);
         break;
 
       case 'Autocomplete-Select':
@@ -1049,10 +1015,8 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
         }
         if ($field->data_type == 'ContactReference') {
           $attributes['class'] = (isset($attributes['class']) ? $attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
-          $attributes['data-api-entity'] = 'contact';
-          $qf->add('text', $elementName, $label, $attributes,
-            $useRequired && !$search
-          );
+          $attributes['data-api-entity'] = 'Contact';
+          $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
 
           $urlParams = "context=customfield&id={$field->id}";
 
@@ -1072,7 +1036,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
               'params' => array('option_group_id' => $field->option_group_id),
             ),
           );
-          $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
+          $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
         }
 
         $qf->assign('customUrls', $customUrls);
@@ -1119,6 +1083,7 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
     if ($field->is_view && !$search) {
       $qf->freeze($elementName);
     }
+    return $element;
   }
 
   /**
@@ -1161,22 +1126,13 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
       throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
     }
 
-    if (!isset(self::$displayInfoCache[$fieldId])) {
-      if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
-        $field = new CRM_Core_BAO_CustomField();
-        $field->id = $fieldId;
-      }
-      $options = $field->getOptions();
-      self::$displayInfoCache[$fieldId] = array(
-        'id' => $fieldId,
-        'html_type' => $field->html_type,
-        'data_type' => $field->data_type,
-        'date_format' => $field->date_format,
-        'time_format' => $field->time_format,
-        'options' => $options,
-      );
+    if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
+      $field = self::getFieldObject($fieldId);
     }
-    return self::formatDisplayValue($value, self::$displayInfoCache[$fieldId], $contactId);
+
+    $fieldInfo = array('options' => $field->getOptions()) + (array) $field;
+
+    return self::formatDisplayValue($value, $fieldInfo, $contactId);
   }
 
   /**
@@ -1184,14 +1140,14 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
    *
    * @param string|array $value
    * @param array $field
-   * @param int|null $contactID
+   * @param int|null $entityId
    *
    * @return string
    */
-  private static function formatDisplayValue($value, $field, $contactID = NULL) {
+  private static function formatDisplayValue($value, $field, $entityId = NULL) {
 
     if (self::isSerialized($field) && !is_array($value)) {
-      $value = (array) CRM_Utils_Array::explodePadded($value);
+      $value = CRM_Utils_Array::explodePadded($value);
     }
     // CRM-12989 fix
     if ($field['html_type'] == 'CheckBox') {
@@ -1230,6 +1186,10 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
       case 'Select Date':
         $customFormat = NULL;
 
+        // FIXME: Are there any legitimate reasons why $value would be an array?
+        // Or should we throw an exception here if it is?
+        $value = is_array($value) ? CRM_Utils_Array::first($value) : $value;
+
         $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats();
         $format = CRM_Utils_Array::value('date_format', $field);
 
@@ -1257,16 +1217,18 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
 
       case 'File':
         // In the context of displaying a profile, show file/image
-        if ($contactID && $value) {
-          $url = self::getFileURL($contactID, $field['id'], $value);
-          if ($url) {
-            $display = $url['file_url'];
+        if ($value) {
+          if ($entityId) {
+            $url = self::getFileURL($entityId, $field['id']);
+            if ($url) {
+              $display = $url['file_url'];
+            }
+          }
+          else {
+            // In other contexts show a paperclip icon
+            $icons = CRM_Core_BAO_File::paperIconAttachment('*', $value);
+            $display = $icons[$value];
           }
-        }
-        // In other contexts show a paperclip icon
-        elseif ($value) {
-          $icons = CRM_Core_BAO_File::paperIconAttachment('*', $value);
-          $display = $icons[$value];
         }
         break;
 
@@ -1366,17 +1328,6 @@ class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
         }
         break;
 
-      case 'Select Date':
-        if ($value) {
-          list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date::setDateDefaults(
-            $value,
-            NULL,
-            $customField->date_format,
-            $customField->time_format
-          );
-        }
-        break;
-
       case 'Autocomplete-Select':
         if ($customField->data_type == 'ContactReference') {
           if (is_numeric($value)) {
@@ -2414,6 +2365,16 @@ WHERE cf.id = %1 AND cg.is_multiple = 1";
     return ($field['html_type'] == 'CheckBox' || strpos($field['html_type'], 'Multi') !== FALSE);
   }
 
+  /**
+   * Get api entity for this field
+   *
+   * @return string
+   */
+  public function getEntity() {
+    $entity = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id, 'extends');
+    return in_array($entity, array('Individual', 'Household', 'Organization')) ? 'Contact' : $entity;
+  }
+
   /**
    * Set pseudoconstant properties for field metadata.
    *