/**
  * Process the form when submitted.
  *
  * @return void
  */
 public function postProcess()
 {
     $field = new CRM_Core_DAO_CustomField();
     $field->id = $this->_id;
     $field->find(TRUE);
     CRM_Core_BAO_CustomField::deleteField($field);
     // also delete any profiles associted with this custom field
     CRM_Core_Session::setStatus(ts('The custom field \'%1\' has been deleted.', array(1 => $field->label)), '', 'success');
 }
Example #2
0
 /**
    * Helper function to create Custom Field
    * @deprecated use parent object create fn
    * @param $params
    * @param null $fields
    * @return object of created field
 */
 static function createField($params, $fields = NULL)
 {
     if (empty($params)) {
         $params = array('custom_group_id' => $fields['groupId'], 'label' => empty($fields['label']) ? 'test_' . CRM_Utils_Array::value('dataType', $fields) : $fields['label'], 'html_type' => CRM_Utils_Array::value('htmlType', $fields), 'data_type' => CRM_Utils_Array::value('dataType', $fields), 'weight' => 4, 'is_required' => 1, 'is_searchable' => 0, 'is_active' => 1, 'version' => 3);
     }
     $result = civicrm_api('custom_field', 'create', $params);
     if ($result['is_error']) {
         print_r($result);
         return NULL;
     }
     // this is done for backward compatibility
     // with tests older than 3.2.3
     $customField = new CRM_Core_DAO_CustomField();
     $customField->id = $result['id'];
     $customField->find(TRUE);
     return $customField;
 }
 /**
  * set up variables to build the form
  *
  * @return void
  * @acess protected
  */
 function preProcess()
 {
     $this->_id = $this->get('id');
     $defaults = array();
     $params = array('id' => $this->_id);
     CRM_Core_BAO_CustomGroup::retrieve($params, $defaults);
     $this->_title = $defaults['title'];
     //check wheter this contain any custom fields
     $customField = new CRM_Core_DAO_CustomField();
     $customField->custom_group_id = $this->_id;
     if ($customField->find(TRUE)) {
         CRM_Core_Session::setStatus(ts("The Group '%1' cannot be deleted! You must Delete all custom fields in this group prior to deleting the group.", array(1 => $this->_title)), ts('Deletion Error'), 'error');
         $url = CRM_Utils_System::url('civicrm/admin/custom/group', "reset=1");
         CRM_Utils_System::redirect($url);
         return TRUE;
     }
     $this->assign('title', $this->_title);
     CRM_Utils_System::setTitle(ts('Confirm Custom Group Delete'));
 }
 function upgrade_3_3_alpha1($rev)
 {
     $config = CRM_Core_Config::singleton();
     if ($config->userSystem->is_drupal) {
         // CRM-6426 - make civicrm profiles permissioned on drupal my account
         $config->userSystem->updateCategories();
     }
     // CRM-6846
     // insert name column for custom field table.
     // make sure name for custom field, group and
     // profile should be unique and properly munged.
     $colQuery = 'ALTER TABLE `civicrm_custom_field` ADD `name` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL AFTER `custom_group_id` ';
     CRM_Core_DAO::executeQuery($colQuery, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
     $customFldCntQuery = 'select count(*) from civicrm_custom_field where name like %1 and id != %2';
     $customField = new CRM_Core_DAO_CustomField();
     $customField->selectAdd();
     $customField->selectAdd('id, label');
     $customField->find();
     while ($customField->fetch()) {
         $name = CRM_Utils_String::munge($customField->label, '_', 64);
         $fldCnt = CRM_Core_DAO::singleValueQuery($customFldCntQuery, array(1 => array($name, 'String'), 2 => array($customField->id, 'Integer')), TRUE, FALSE);
         if ($fldCnt) {
             $name = CRM_Utils_String::munge("{$name}_" . rand(), '_', 64);
         }
         $customFieldQuery = "\nUpdate `civicrm_custom_field`\nSET `name` = %1\nWHERE id = %2\n";
         $customFieldParams = array(1 => array($name, 'String'), 2 => array($customField->id, 'Integer'));
         CRM_Core_DAO::executeQuery($customFieldQuery, $customFieldParams, TRUE, NULL, FALSE, FALSE);
     }
     $customField->free();
     $customGrpCntQuery = 'select count(*) from civicrm_custom_group where name like %1 and id != %2';
     $customGroup = new CRM_Core_DAO_CustomGroup();
     $customGroup->selectAdd();
     $customGroup->selectAdd('id, title');
     $customGroup->find();
     while ($customGroup->fetch()) {
         $name = CRM_Utils_String::munge($customGroup->title, '_', 64);
         $grpCnt = CRM_Core_DAO::singleValueQuery($customGrpCntQuery, array(1 => array($name, 'String'), 2 => array($customGroup->id, 'Integer')));
         if ($grpCnt) {
             $name = CRM_Utils_String::munge("{$name}_" . rand(), '_', 64);
         }
         CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup', $customGroup->id, 'name', $name);
     }
     $customGroup->free();
     $ufGrpCntQuery = 'select count(*) from civicrm_uf_group where name like %1 and id != %2';
     $ufGroup = new CRM_Core_DAO_UFGroup();
     $ufGroup->selectAdd();
     $ufGroup->selectAdd('id, title');
     $ufGroup->find();
     while ($ufGroup->fetch()) {
         $name = CRM_Utils_String::munge($ufGroup->title, '_', 64);
         $ufGrpCnt = CRM_Core_DAO::singleValueQuery($ufGrpCntQuery, array(1 => array($name, 'String'), 2 => array($ufGroup->id, 'Integer')));
         if ($ufGrpCnt) {
             $name = CRM_Utils_String::munge("{$name}_" . rand(), '_', 64);
         }
         CRM_Core_DAO::setFieldValue('CRM_Core_DAO_UFGroup', $ufGroup->id, 'name', $name);
     }
     $ufGroup->free();
     $upgrade = new CRM_Upgrade_Form();
     $upgrade->processSQL($rev);
     // now modify the config so that the directories are stored in option group/value
     // CRM-6914
     // require_once 'CRM/Core/BAO/ConfigSetting.php';
     // $params = array( );
     // CRM_Core_BAO_ConfigSetting::add( $parambs );
 }
 /**
  * Low-level option getter, rarely accessed directly.
  * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
  *
  * @param String $daoName
  * @param String $fieldName
  * @param Array $params
  * - name       string  name of the option group
  * - flip       boolean results are return in id => label format if false
  *                            if true, the results are reversed
  * - grouping   boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
  * - localize   boolean if true, localize the results before returning
  * - condition  string|array add condition(s) to the sql query - will be concatenated using 'AND'
  * - keyColumn  string the column to use for 'id'
  * - labelColumn string the column to use for 'label'
  * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
  * - onlyActive boolean return only the action option values
  * - fresh      boolean ignore cache entries and go back to DB
  * @param String $context: Context string
  *
  * @return Array on success, FALSE on error.
  *
  * @static
  */
 public static function get($daoName, $fieldName, $params = array(), $context = NULL)
 {
     CRM_Core_DAO::buildOptionsContext($context);
     $flip = !empty($params['flip']);
     // Merge params with defaults
     $params += array('grouping' => FALSE, 'localize' => FALSE, 'onlyActive' => $context == 'validate' || $context == 'get' ? FALSE : TRUE, 'fresh' => FALSE);
     // Custom fields are not in the schema
     if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
         $customField = new CRM_Core_DAO_CustomField();
         $customField->id = (int) substr($fieldName, 7);
         $customField->find(TRUE);
         $options = FALSE;
         if (!empty($customField->option_group_id)) {
             $options = CRM_Core_OptionGroup::valuesByID($customField->option_group_id, $flip, $params['grouping'], $params['localize'], CRM_Utils_Array::value('labelColumn', $params, 'label'), $params['onlyActive'], $params['fresh']);
         } else {
             if ($customField->data_type === 'StateProvince') {
                 $options = self::stateProvince();
             } elseif ($customField->data_type === 'Country') {
                 $options = $context == 'validate' ? self::countryIsoCode() : self::country();
             } elseif ($customField->data_type === 'Boolean') {
                 $options = $context == 'validate' ? array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
             }
             $options = $options && $flip ? array_flip($options) : $options;
         }
         if ($options !== FALSE) {
             CRM_Utils_Hook::customFieldOptions($customField->id, $options, FALSE);
         }
         $customField->free();
         return $options;
     }
     // Core field: load schema
     $dao = new $daoName();
     $fields = $dao->fields();
     $fieldKeys = $dao->fieldKeys();
     $dao->free();
     // Support "unique names" as well as sql names
     $fieldKey = $fieldName;
     if (empty($fields[$fieldKey])) {
         $fieldKey = CRM_Utils_Array::value($fieldName, $fieldKeys);
     }
     // If neither worked then this field doesn't exist. Return false.
     if (empty($fields[$fieldKey])) {
         return FALSE;
     }
     $fieldSpec = $fields[$fieldKey];
     // If the field is an enum, explode the enum definition and return the array.
     if (isset($fieldSpec['enumValues'])) {
         // use of a space after the comma is inconsistent in xml
         $enumStr = str_replace(', ', ',', $fieldSpec['enumValues']);
         $output = explode(',', $enumStr);
         return array_combine($output, $output);
     } elseif (!empty($fieldSpec['pseudoconstant'])) {
         $pseudoconstant = $fieldSpec['pseudoconstant'];
         // Merge params with schema defaults
         $params += array('condition' => CRM_Utils_Array::value('condition', $pseudoconstant, array()), 'keyColumn' => CRM_Utils_Array::value('keyColumn', $pseudoconstant), 'labelColumn' => CRM_Utils_Array::value('labelColumn', $pseudoconstant));
         // Fetch option group from option_value table
         if (!empty($pseudoconstant['optionGroupName'])) {
             if ($context == 'validate') {
                 $params['labelColumn'] = 'name';
             }
             // Call our generic fn for retrieving from the option_value table
             return CRM_Core_OptionGroup::values($pseudoconstant['optionGroupName'], $flip, $params['grouping'], $params['localize'], $params['condition'] ? ' AND ' . implode(' AND ', (array) $params['condition']) : NULL, $params['labelColumn'] ? $params['labelColumn'] : 'label', $params['onlyActive'], $params['fresh'], $params['keyColumn'] ? $params['keyColumn'] : 'value');
         }
         // Fetch options from other tables
         if (!empty($pseudoconstant['table'])) {
             // Normalize params so the serialized cache string will be consistent.
             CRM_Utils_Array::remove($params, 'flip', 'fresh');
             ksort($params);
             $cacheKey = $daoName . $fieldName . serialize($params);
             // Retrieve cached options
             if (isset(self::$cache[$cacheKey]) && empty($params['fresh'])) {
                 $output = self::$cache[$cacheKey];
             } else {
                 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($pseudoconstant['table']);
                 if (!class_exists($daoName)) {
                     return FALSE;
                 }
                 // Get list of fields for the option table
                 $dao = new $daoName();
                 $availableFields = array_keys($dao->fieldKeys());
                 $dao->free();
                 $select = "SELECT %1 AS id, %2 AS label";
                 $from = "FROM %3";
                 $wheres = array();
                 $order = "ORDER BY %2";
                 // Use machine name instead of label in validate context
                 if ($context == 'validate') {
                     if (!empty($pseudoconstant['nameColumn'])) {
                         $params['labelColumn'] = $pseudoconstant['nameColumn'];
                     } elseif (in_array('name', $availableFields)) {
                         $params['labelColumn'] = 'name';
                     }
                 }
                 // Condition param can be passed as an sql clause string or an array of clauses
                 if (!empty($params['condition'])) {
                     $wheres[] = implode(' AND ', (array) $params['condition']);
                 }
                 // onlyActive param will automatically filter on common flags
                 if (!empty($params['onlyActive'])) {
                     foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0) as $flag => $val) {
                         if (in_array($flag, $availableFields)) {
                             $wheres[] = "{$flag} = {$val}";
                         }
                     }
                 }
                 // Filter domain specific options
                 if (in_array('domain_id', $availableFields)) {
                     $wheres[] = 'domain_id = ' . CRM_Core_Config::domainID();
                 }
                 $queryParams = array(1 => array($params['keyColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES), 2 => array($params['labelColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES), 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES));
                 // Add orderColumn param
                 if (!empty($params['orderColumn'])) {
                     $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES);
                     $order = "ORDER BY %4";
                 } elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
                     $order = '';
                 } elseif (in_array('weight', $availableFields)) {
                     $order = "ORDER BY weight";
                 }
                 $output = array();
                 $query = "{$select} {$from}";
                 if ($wheres) {
                     $query .= " WHERE " . implode($wheres, ' AND ');
                 }
                 $query .= ' ' . $order;
                 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
                 while ($dao->fetch()) {
                     $output[$dao->id] = $dao->label;
                 }
                 $dao->free();
                 // Localize results
                 if (!empty($params['localize']) || $pseudoconstant['table'] == 'civicrm_country' || $pseudoconstant['table'] == 'civicrm_state_province') {
                     $I18nParams = array();
                     if ($pseudoconstant['table'] == 'civicrm_country') {
                         $I18nParams['context'] = 'country';
                     }
                     if ($pseudoconstant['table'] == 'civicrm_state_province') {
                         $I18nParams['context'] = 'province';
                     }
                     $i18n = CRM_Core_I18n::singleton();
                     $i18n->localizeArray($output, $I18nParams);
                     // Maintain sort by label
                     if ($order == "ORDER BY %2") {
                         CRM_Utils_Array::asort($output);
                     }
                 }
                 self::$cache[$cacheKey] = $output;
             }
             return $flip ? array_flip($output) : $output;
         }
     } elseif (CRM_Utils_Array::value('type', $fieldSpec) === CRM_Utils_Type::T_BOOLEAN) {
         $output = $context == 'validate' ? array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
         return $flip ? array_flip($output) : $output;
     }
     // If we're still here, it's an error. Return FALSE.
     return FALSE;
 }
Example #6
0
 /**
  * Process the form when submitted
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // step 1: copy and create dstField and column
     require_once 'CRM/Core/BAO/CustomField.php';
     $field = new CRM_Core_DAO_CustomField();
     $field->id = $this->_srcFID;
     if (!$field->find(true)) {
         CRM_Core_Error::fatal();
     }
     // now change the field group ID and save it, also unset the id
     unset($field->id);
     // step 2: copy data from srcColumn to dstColumn
     $query = "\nINSERT INTO {$dstTable} ( {$entityID}, {$dstColumn} )\nSELECT {$entityID}, {$srcColumn}\nFROM   {$srcTable}\nON DUPLICATE KEY UPDATE {$dstColumn} = {$srcColumn}";
     CRM_Core_DAO::query($query, CRM_Core_DAO::$_nullArray);
     // step 3: remove srcField (which should also delete the srcColumn
     require_once 'CRM/Core/BAO/CustomField.php';
     $field = new CRM_Core_DAO_CustomField();
     $field->id = $this->_srcFID;
     CRM_Core_BAO_CustomField::deleteField($field);
 }
Example #7
0
 /**
  * global validation rules for the form
  *
  * @param array $fields posted values of the form
  *
  * @return array list of errors to be posted back to the form
  * @static
  * @access public
  */
 static function formRule($fields, $files, $self)
 {
     $is_required = CRM_Utils_Array::value('is_required', $fields, false);
     $is_registration = CRM_Utils_Array::value('is_registration', $fields, false);
     $is_view = CRM_Utils_Array::value('is_view', $fields, false);
     $in_selector = CRM_Utils_Array::value('in_selector', $fields, false);
     $is_searchable = CRM_Utils_Array::value('is_searchable', $fields, false);
     $visibility = CRM_Utils_Array::value('visibility', $fields, false);
     $is_active = CRM_Utils_Array::value('is_active', $fields, false);
     $errors = array();
     if ($is_view && $is_registration) {
         $errors['is_registration'] = ts('View Only cannot be selected if this field is to be included on the registration form');
     }
     if ($is_view && $is_required) {
         $errors['is_view'] = ts('A View Only field cannot be required');
     }
     $fieldName = $fields['field_name'][0];
     if (!$fieldName) {
         $errors['field_name'] = ts('Please select a field name');
     }
     if ($in_selector && in_array($fieldName, array('Contribution', 'Participant', 'Membership', 'Activity'))) {
         $errors['in_selector'] = ts("'In Selector' cannot be checked for %1 fields.", array(1 => $fieldName));
     }
     if (!empty($fields['field_id'])) {
         //get custom field id
         $customFieldId = explode('_', $fieldName);
         if ($customFieldId[0] == 'custom') {
             $customField = new CRM_Core_DAO_CustomField();
             $customField->id = $customFieldId[1];
             $customField->find(true);
             if (!$customField->is_active && $is_active) {
                 $errors['field_name'] = ts('Cannot set this field "Active" since the selected custom field is disabled.');
             }
         }
     }
     //check profile is configured for double option process
     //adding group field, email field should be present in the group
     //fixed for  issue CRM-2861 & CRM-4153
     $config = CRM_Core_Config::singleton();
     if ($config->profileDoubleOptIn) {
         if ($fields['field_name'][1] == 'group') {
             require_once 'CRM/Core/BAO/UFField.php';
             $dao = new CRM_Core_BAO_UFField();
             $dao->uf_group_id = $fields['group_id'];
             $dao->find();
             $emailField = false;
             while ($dao->fetch()) {
                 //check email field is present in the group
                 if ($dao->field_name == 'email') {
                     $emailField = true;
                 }
             }
             if (!$emailField) {
                 $disableSetting = "define( 'CIVICRM_PROFILE_DOUBLE_OPTIN' , 0 );";
                 $errors['field_name'] = ts('Your site is currently configured to require double-opt in when users join (subscribe) to Group(s) via a Profile form. In this mode, you need to include an Email field in a Profile BEFORE you can add the Group(s) field. This ensures that an opt-in confirmation email can be sent. Your site administrator can disable double opt-in by adding this line to the CiviCRM settings file: <em>%1</em>', array(1 => $disableSetting));
             }
         }
     }
     //fix for CRM-3037
     $fieldType = $fields['field_name'][0];
     //get the group type.
     $groupType = CRM_Core_BAO_UFGroup::calculateGroupType($self->_gid, CRM_Utils_Array::value('field_id', $fields));
     switch ($fieldType) {
         case 'Contact':
             if (in_array('Activity', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Contact with combination of Activity');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Individual':
             if (in_array('Activity', $groupType) || in_array('Household', $groupType) || in_array('Organization', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Individual with combination of Household or Organization or Activity');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Household':
             if (in_array('Activity', $groupType) || in_array('Individual', $groupType) || in_array('Organization', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Household with combination of Individual or Organization or Activity');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Organization':
             if (in_array('Activity', $groupType) || in_array('Household', $groupType) || in_array('Individual', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Organization with combination of Household or Individual or Activity');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Activity':
             if (in_array('Individual', $groupType) || in_array('Membership', $groupType) || in_array('Contribution', $groupType) || in_array('Organization', $groupType) || in_array('Household', $groupType) || in_array('Participant', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Activity with combination Participant or Membership or Contribution or Household or Organization or Individual');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Participant':
             if (in_array('Membership', $groupType) || in_array('Contribution', $groupType) || in_array('Organization', $groupType) || in_array('Household', $groupType) || in_array('Activity', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Participant with combination of Activity or Membership or Contribution or Household or Organization or Activity');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Contribution':
             if (in_array('Participant', $groupType) || in_array('Membership', $groupType) || in_array('Organization', $groupType) || in_array('Household', $groupType) || in_array('Activity', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Contribution with combination of Activity or Membership or Participant or Household or Organization');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Membership':
             if (in_array('Participant', $groupType) || in_array('Contribution', $groupType) || in_array('Organization', $groupType) || in_array('Household', $groupType) || in_array('Activity', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Membership with combination of Activity or Participant or Contribution or Household or Organization');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         default:
             $profileType = CRM_Core_BAO_UFField::getProfileType($fields['group_id'], true, false, true);
             if (CRM_Contact_BAO_ContactType::isaSubType($fieldType)) {
                 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
                     if ($fieldType != $profileType) {
                         $errors['field_name'] = ts('Cannot add or update profile field type "%1" with combination of "%2".', array(1 => $fieldType, 2 => $profileType));
                     }
                 } else {
                     $basicType = CRM_Contact_BAO_ContactType::getBasicType($fieldType);
                     if ($profileType && $profileType != $basicType && $profileType != 'Contact') {
                         $errors['field_name'] = ts('Cannot add or update profile field type "%1" with combination of "%2".', array(1 => $fieldType, 2 => $profileType));
                     }
                 }
             } elseif ($fields['field_name'][1] == 'contact_sub_type' && !in_array($profileType, array('Individual', 'Household', 'Organization')) && !in_array($profileType, CRM_Contact_BAO_ContactType::subTypes())) {
                 $errors['field_name'] = ts('Cannot add or update profile field Contact Subtype as profile type is not one of Individual, Household or Organization.');
             }
     }
     return empty($errors) ? true : $errors;
 }
Example #8
0
 /**
  * Check the status of custom field used in uf fields.
  *
  * @param int $UFFieldId
  *
  * @return bool
  *   false if custom field are disabled else true
  */
 public static function checkUFStatus($UFFieldId)
 {
     $fieldName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFField', $UFFieldId, 'field_name');
     // return if field is not a custom field
     if (!($customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldName))) {
         return TRUE;
     }
     $customField = new CRM_Core_DAO_CustomField();
     $customField->id = $customFieldId;
     // if uf field is custom field
     if ($customField->find(TRUE)) {
         if (!$customField->is_active) {
             return FALSE;
         } else {
             return TRUE;
         }
     }
 }
Example #9
0
 /**
  * global validation rules for the form
  *
  * @param array  $fields   (referance) posted values of the form
  *
  * @return array    if errors then list of errors to be posted back to the form,
  *                  true otherwise
  * @static
  * @access public
  */
 static function formRule(&$fields, &$files, &$self)
 {
     $default = CRM_Utils_Array::value('default_value', $fields);
     $errors = array();
     // ensure that the label is not 'id'
     if (strtolower($fields['label']) == 'id') {
         $errors['label'] = ts("You cannot use 'id' as a field label.");
     }
     $customField = new CRM_Core_DAO_CustomField();
     $customField->custom_group_id = $self->_gid;
     $customField->label = $fields['label'];
     $dupeLabel = false;
     if ($customField->find(true) && $self->_id != $customField->id) {
         $dupeLabel = true;
     }
     if ($dupeLabel) {
         $errors['label'] = ts('Name already exists in Database.');
     }
     if (!isset($fields['data_type'][0]) || !isset($fields['data_type'][1])) {
         $errors['_qf_default'] = ts('Please enter valid - Data and Input Field Type.');
     }
     if ($default) {
         $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
         switch ($dataType) {
             case 'Int':
                 if (!CRM_Utils_Rule::integer($default)) {
                     $errors['default_value'] = ts('Please enter a valid integer as default value.');
                 }
                 break;
             case 'Float':
                 if (!CRM_Utils_Rule::numeric($default)) {
                     $errors['default_value'] = ts('Please enter a valid number as default value.');
                 }
                 break;
             case 'Money':
                 if (!CRM_Utils_Rule::money($default)) {
                     $errors['default_value'] = ts('Please enter a valid number value.');
                 }
                 break;
             case 'Link':
                 if (!CRM_Utils_Rule::url($default)) {
                     $errors['default_value'] = ts('Please enter a valid link.');
                 }
                 break;
             case 'Date':
                 if (!CRM_Utils_Rule::date($default)) {
                     $errors['default_value'] = ts('Please enter a valid date as default value using YYYY-MM-DD format. Example: 2004-12-31.');
                 }
                 break;
             case 'Boolean':
                 if ($default != '1' && $default != '0') {
                     $errors['default_value'] = ts('Please enter 1 (for Yes) or 0 (for No) if you want to set a default value.');
                 }
                 break;
             case 'Country':
                 if (!empty($default)) {
                     $query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
                     $params = array(1 => array($fields['default_value'], 'String'));
                     if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
                         $errors['default_value'] = ts('Invalid default value for country.');
                     }
                 }
                 break;
             case 'StateProvince':
                 if (!empty($default)) {
                     $query = "\nSELECT count(*) \n  FROM civicrm_state_province\n WHERE name = %1\n    OR abbreviation = %1";
                     $params = array(1 => array($fields['default_value'], 'String'));
                     if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
                         $errors['default_value'] = ts('The invalid default value for State/Province data type');
                     }
                 }
                 break;
             case 'ContactReference':
                 //FIX ME
                 break;
         }
     }
     if (self::$_dataTypeKeys[$fields['data_type'][0]] == 'Date') {
         if (!$fields['date_format']) {
             $errors['date_format'] = ts('Please select a date format.');
         }
     }
     /** Check the option values entered
      *  Appropriate values are required for the selected datatype
      *  Incomplete row checking is also required.
      */
     $_flagOption = $_rowError = 0;
     $_showHide =& new CRM_Core_ShowHideBlocks('', '');
     $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
     if (isset($fields['data_type'][1])) {
         $dataField = $fields['data_type'][1];
     }
     $optionFields = array('Select', 'Multi-Select', 'CheckBox', 'Radio', 'AdvMulti-Select');
     if ($fields['option_type'] == 1) {
         //capture duplicate Custom option values
         if (!empty($fields['option_value'])) {
             $countValue = count($fields['option_value']);
             $uniqueCount = count(array_unique($fields['option_value']));
             if ($countValue > $uniqueCount) {
                 $start = 1;
                 while ($start < self::NUM_OPTION) {
                     $nextIndex = $start + 1;
                     while ($nextIndex <= self::NUM_OPTION) {
                         if ($fields['option_value'][$start] == $fields['option_value'][$nextIndex] && !empty($fields['option_value'][$nextIndex])) {
                             $errors['option_value[' . $start . ']'] = ts('Duplicate Option values');
                             $errors['option_value[' . $nextIndex . ']'] = ts('Duplicate Option values');
                             $_flagOption = 1;
                         }
                         $nextIndex++;
                     }
                     $start++;
                 }
             }
         }
         //capture duplicate Custom Option label
         if (!empty($fields['option_label'])) {
             $countValue = count($fields['option_label']);
             $uniqueCount = count(array_unique($fields['option_label']));
             if ($countValue > $uniqueCount) {
                 $start = 1;
                 while ($start < self::NUM_OPTION) {
                     $nextIndex = $start + 1;
                     while ($nextIndex <= self::NUM_OPTION) {
                         if ($fields['option_label'][$start] == $fields['option_label'][$nextIndex] && !empty($fields['option_label'][$nextIndex])) {
                             $errors['option_label[' . $start . ']'] = ts('Duplicate Option label');
                             $errors['option_label[' . $nextIndex . ']'] = ts('Duplicate Option label');
                             $_flagOption = 1;
                         }
                         $nextIndex++;
                     }
                     $start++;
                 }
             }
         }
         for ($i = 1; $i <= self::NUM_OPTION; $i++) {
             if (!$fields['option_label'][$i]) {
                 if ($fields['option_value'][$i]) {
                     $errors['option_label[' . $i . ']'] = ts('Option label cannot be empty');
                     $_flagOption = 1;
                 } else {
                     $_emptyRow = 1;
                 }
             } else {
                 if (!strlen(trim($fields['option_value'][$i]))) {
                     if (!$fields['option_value'][$i]) {
                         $errors['option_value[' . $i . ']'] = ts('Option value cannot be empty');
                         $_flagOption = 1;
                     }
                 }
             }
             if ($fields['option_value'][$i] && $dataType != 'String') {
                 if ($dataType == 'Int') {
                     if (!CRM_Utils_Rule::integer($fields['option_value'][$i])) {
                         $_flagOption = 1;
                         $errors['option_value[' . $i . ']'] = ts('Please enter a valid integer.');
                     }
                 } else {
                     if ($dataType == 'Money') {
                         if (!CRM_Utils_Rule::money($fields['option_value'][$i])) {
                             $_flagOption = 1;
                             $errors['option_value[' . $i . ']'] = ts('Please enter a valid money value.');
                         }
                     } else {
                         if (!CRM_Utils_Rule::numeric($fields['option_value'][$i])) {
                             $_flagOption = 1;
                             $errors['option_value[' . $i . ']'] = ts('Please enter a valid number.');
                         }
                     }
                 }
             }
             $showBlocks = 'optionField_' . $i;
             if ($_flagOption) {
                 $_showHide->addShow($showBlocks);
                 $_rowError = 1;
             }
             if (!empty($_emptyRow)) {
                 $_showHide->addHide($showBlocks);
             } else {
                 $_showHide->addShow($showBlocks);
             }
             if ($i == self::NUM_OPTION) {
                 $hideBlock = 'additionalOption';
                 $_showHide->addHide($hideBlock);
             }
             $_flagOption = $_emptyRow = 0;
         }
     } elseif (isset($dataField) && in_array($dataField, $optionFields) && !in_array($dataType, array('Boolean', 'Country', 'StateProvince'))) {
         if (!$fields['option_group_id']) {
             $errors['option_group_id'] = ts('You must select a Multiple Choice Option set if you chose Reuse an existing set.');
         } else {
             $query = "\nSELECT count(*)\nFROM   civicrm_custom_field\nWHERE  data_type != %1\nAND    option_group_id = %2";
             $params = array(1 => array(self::$_dataTypeKeys[$fields['data_type'][0]], 'String'), 2 => array($fields['option_group_id'], 'Integer'));
             $count = CRM_Core_DAO::singleValueQuery($query, $params);
             if ($count > 0) {
                 $errors['option_group_id'] = ts('The data type of the multiple choice option set you\'ve selected does not match the data type assigned to this field.');
             }
         }
     }
     if ($_rowError) {
         $_showHide->addToTemplate();
         CRM_Core_Page::assign('optionRowError', $_rowError);
     } else {
         if (isset($fields['data_type'][1])) {
             switch (self::$_dataToHTML[$fields['data_type'][0]][$fields['data_type'][1]]) {
                 case 'Radio':
                     $_fieldError = 1;
                     CRM_Core_Page::assign('fieldError', $_fieldError);
                     break;
                 case 'Checkbox':
                     $_fieldError = 1;
                     CRM_Core_Page::assign('fieldError', $_fieldError);
                     break;
                 case 'Select':
                     $_fieldError = 1;
                     CRM_Core_Page::assign('fieldError', $_fieldError);
                     break;
                 default:
                     $_fieldError = 0;
                     CRM_Core_Page::assign('fieldError', $_fieldError);
             }
         }
         for ($idx = 1; $idx <= self::NUM_OPTION; $idx++) {
             $showBlocks = 'optionField_' . $idx;
             if (!empty($fields['option_label'][$idx])) {
                 $_showHide->addShow($showBlocks);
             } else {
                 $_showHide->addHide($showBlocks);
             }
         }
         $_showHide->addToTemplate();
     }
     //checks the given custom field name doesnot start with digit
     $title = $fields['label'];
     if (!empty($title)) {
         $asciiValue = ord($title[0]);
         //gives the ascii value
         if ($asciiValue >= 48 && $asciiValue <= 57) {
             $errors['label'] = ts("Field's Name should not start with digit");
         }
     }
     // we can not set require and view at the same time.
     if (CRM_Utils_Array::value('is_required', $fields) && CRM_Utils_Array::value('is_view', $fields)) {
         $errors['is_view'] = ts('Can not set this field Required and View Only at the same time.');
     }
     return empty($errors) ? true : $errors;
 }
Example #10
0
 /**
  * Global validation rules for the form.
  *
  * @param array $fields
  *   Posted values of the form.
  *
  * @param $files
  * @param $self
  *
  * @return array
  *   list of errors to be posted back to the form
  */
 public static function formRule($fields, $files, $self)
 {
     $is_required = CRM_Utils_Array::value('is_required', $fields, FALSE);
     $is_registration = CRM_Utils_Array::value('is_registration', $fields, FALSE);
     $is_view = CRM_Utils_Array::value('is_view', $fields, FALSE);
     $in_selector = CRM_Utils_Array::value('in_selector', $fields, FALSE);
     $is_active = CRM_Utils_Array::value('is_active', $fields, FALSE);
     $errors = array();
     if ($is_view && $is_registration) {
         $errors['is_registration'] = ts('View Only cannot be selected if this field is to be included on the registration form');
     }
     if ($is_view && $is_required) {
         $errors['is_view'] = ts('A View Only field cannot be required');
     }
     $entityName = $fields['field_name'][0];
     if (!$entityName) {
         $errors['field_name'] = ts('Please select a field name');
     }
     if ($in_selector && in_array($entityName, array('Contribution', 'Participant', 'Membership', 'Activity'))) {
         $errors['in_selector'] = ts("'In Selector' cannot be checked for %1 fields.", array(1 => $entityName));
     }
     $isCustomField = FALSE;
     $profileFieldName = CRM_Utils_Array::value(1, $fields['field_name']);
     if ($profileFieldName) {
         //get custom field id
         $customFieldId = explode('_', $profileFieldName);
         if ($customFieldId[0] == 'custom') {
             $customField = new CRM_Core_DAO_CustomField();
             $customField->id = $customFieldId[1];
             $customField->find(TRUE);
             $isCustomField = TRUE;
             if (!empty($fields['field_id']) && !$customField->is_active && $is_active) {
                 $errors['field_name'] = ts('Cannot set this field "Active" since the selected custom field is disabled.');
             }
             //check if profile already has a different multi-record custom set field configured
             $customGroupId = CRM_Core_BAO_CustomField::isMultiRecordField($profileFieldName);
             if ($customGroupId) {
                 if ($profileMultiRecordCustomGid = CRM_Core_BAO_UFField::checkMultiRecordFieldExists($self->_gid)) {
                     if ($customGroupId != $profileMultiRecordCustomGid) {
                         $errors['field_name'] = ts("You cannot configure multi-record custom fields belonging to different custom sets in one profile");
                     }
                 }
             }
         }
     }
     // Get list of fields already in the group
     $groupFields = CRM_Core_BAO_UFGroup::getFields($fields['group_id'], FALSE, NULL, NULL, NULL, TRUE, NULL, TRUE);
     // Check if we already added a primary field of the same communication type
     self::formRulePrimaryCheck($fields, $profileFieldName, $groupFields, $errors);
     //check profile is configured for double option process
     //adding group field, email field should be present in the group
     //fixed for  issue CRM-2861 & CRM-4153
     if (CRM_Core_BAO_UFGroup::isProfileDoubleOptin()) {
         if (CRM_Utils_Array::value(1, $fields['field_name']) == 'group') {
             $dao = new CRM_Core_BAO_UFField();
             $dao->uf_group_id = $fields['group_id'];
             $dao->find();
             $emailField = FALSE;
             while ($dao->fetch()) {
                 //check email field is present in the group
                 if ($dao->field_name == 'email') {
                     $emailField = TRUE;
                     break;
                 }
             }
             if (!$emailField) {
                 $disableSettingURL = CRM_Utils_System::url('civicrm/admin/setting/preferences/mailing', 'reset=1');
                 $errors['field_name'] = ts('Your site is currently configured to require double-opt in when users join (subscribe) to Group(s) via a Profile form. In this mode, you need to include an Email field in a Profile BEFORE you can add the Group(s) field. This ensures that an opt-in confirmation email can be sent. Your site administrator can disable double opt-in on the civimail admin settings: <em>%1</em>', array(1 => $disableSettingURL));
             }
         }
     }
     //fix for CRM-3037
     $fieldType = $fields['field_name'][0];
     //get the group type.
     $groupType = CRM_Core_BAO_UFGroup::calculateGroupType($self->_gid, FALSE, CRM_Utils_Array::value('field_id', $fields));
     switch ($fieldType) {
         case 'Contact':
             self::formRuleSubType($fieldType, $groupType, $errors);
             break;
         case 'Individual':
             if (in_array('Activity', $groupType) || in_array('Household', $groupType) || in_array('Organization', $groupType)) {
                 //CRM-7603 - need to support activity + individual.
                 //$errors['field_name'] =
                 //ts( 'Cannot add or update profile field type Individual with combination of Household or Organization or Activity' );
                 if (in_array('Household', $groupType) || in_array('Organization', $groupType)) {
                     $errors['field_name'] = ts('Cannot add or update profile field type Individual with combination of Household or Organization');
                 }
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Household':
             if (in_array('Activity', $groupType) || in_array('Individual', $groupType) || in_array('Organization', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Household with combination of Individual or Organization or Activity');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Organization':
             if (in_array('Activity', $groupType) || in_array('Household', $groupType) || in_array('Individual', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Organization with combination of Household or Individual or Activity');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Activity':
             if (in_array('Individual', $groupType) || in_array('Membership', $groupType) || in_array('Contribution', $groupType) || in_array('Organization', $groupType) || in_array('Household', $groupType) || in_array('Participant', $groupType)) {
                 //CRM-7603 - need to support activity + contact type.
                 //$errors['field_name'] =
                 //ts( 'Cannot add or update profile field type Activity with combination Participant or Membership or Contribution or Household or Organization or Individual' );
                 if (in_array('Membership', $groupType) || in_array('Contribution', $groupType) || in_array('Participant', $groupType)) {
                     $errors['field_name'] = ts('Cannot add or update profile field type Activity with combination Participant or Membership or Contribution');
                 }
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             if ($isCustomField && !isset($errors['field_name'])) {
                 self::formRuleCustomDataExtentColumnValue($customField, $self->_gid, $fieldType, $errors);
             }
             break;
         case 'Participant':
             if (in_array('Membership', $groupType) || in_array('Contribution', $groupType) || in_array('Organization', $groupType) || in_array('Household', $groupType) || in_array('Activity', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Participant with combination of Activity or Membership or Contribution or Household or Organization.');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Contribution':
             //special case where in we allow contribution + oganization fields, for on behalf feature
             $profileId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', 'on_behalf_organization', 'id', 'name');
             if (in_array('Participant', $groupType) || in_array('Membership', $groupType) || $profileId != $self->_gid && in_array('Organization', $groupType) || in_array('Household', $groupType) || in_array('Activity', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Contribution with combination of Activity or Membership or Participant or Household or Organization');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         case 'Membership':
             //special case where in we allow contribution + oganization fields, for on behalf feature
             $profileId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', 'on_behalf_organization', 'id', 'name');
             if (in_array('Participant', $groupType) || in_array('Contribution', $groupType) || $profileId != $self->_gid && in_array('Organization', $groupType) || in_array('Household', $groupType) || in_array('Activity', $groupType)) {
                 $errors['field_name'] = ts('Cannot add or update profile field type Membership with combination of Activity or Participant or Contribution or Household or Organization');
             } else {
                 self::formRuleSubType($fieldType, $groupType, $errors);
             }
             break;
         default:
             $profileType = CRM_Core_BAO_UFField::getProfileType($fields['group_id'], TRUE, FALSE, TRUE);
             if (CRM_Contact_BAO_ContactType::isaSubType($fieldType)) {
                 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
                     if ($fieldType != $profileType) {
                         $errors['field_name'] = ts('Cannot add or update profile field type "%1" with combination of "%2".', array(1 => $fieldType, 2 => $profileType));
                     }
                 } else {
                     $basicType = CRM_Contact_BAO_ContactType::getBasicType($fieldType);
                     if ($profileType && $profileType != $basicType && $profileType != 'Contact') {
                         $errors['field_name'] = ts('Cannot add or update profile field type "%1" with combination of "%2".', array(1 => $fieldType, 2 => $profileType));
                     }
                 }
             } elseif (CRM_Utils_Array::value(1, $fields['field_name']) == 'contact_sub_type' && !in_array($profileType, array('Individual', 'Household', 'Organization')) && !in_array($profileType, CRM_Contact_BAO_ContactType::subTypes())) {
                 $errors['field_name'] = ts('Cannot add or update profile field Contact Subtype as profile type is not one of Individual, Household or Organization.');
             }
     }
     return empty($errors) ? TRUE : $errors;
 }
Example #11
0
 /**
  * Returns the list of fields that can be exported
  *
  * @param bool $prefix
  *
  * @return array
  */
 static function &export($prefix = false)
 {
     if (!self::$_export) {
         self::$_export = array();
         $fields = self::fields();
         foreach ($fields as $name => $field) {
             if (CRM_Utils_Array::value('export', $field)) {
                 if ($prefix) {
                     self::$_export['custom_field'] =& $fields[$name];
                 } else {
                     self::$_export[$name] =& $fields[$name];
                 }
             }
         }
     }
     return self::$_export;
 }
Example #12
0
 /**
  * Process the form when submitted
  *
  * @param null
  * 
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $field = new CRM_Core_DAO_CustomField();
     $field->id = $this->_id;
     $field->find(true);
     CRM_Core_BAO_CustomField::deleteField($field);
     // also delete any profiles associted with this custom field
     require_once "CRM/Core/BAO/UFField.php";
     CRM_Core_BAO_UFField::delUFField($this->_id);
     CRM_Core_Session::setStatus(ts('The custom field \'%1\' has been deleted.', array(1 => $field->label)));
     CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_CustomField');
 }
Example #13
0
/**
 * Use this API to delete an existing custom group field.
 *
 * @param $params     Array id of the field to be deleted
 *
 *       
 * @access public
 **/
function civicrm_custom_field_delete($params)
{
    _civicrm_initialize();
    if (!is_array($params)) {
        return civicrm_create_error('Params is not an array');
    }
    if (!CRM_Utils_Array::value('customFieldId', $params['result'])) {
        return civicrm_create_error('Invalid or no value for Custom Field ID');
    }
    require_once 'CRM/Core/DAO/CustomField.php';
    $field = new CRM_Core_DAO_CustomField();
    $field->id = $params['result']['customFieldId'];
    $field->find(true);
    require_once 'CRM/Core/BAO/CustomField.php';
    $customFieldDelete = CRM_Core_BAO_CustomField::deleteField($field);
    return $customFieldDelete ? civicrm_create_error('Error while deleting custom field') : civicrm_create_success();
}
 /**
  * Delete the Custom Group.
  *
  * @param CRM_Core_BAO_CustomGroup $group
  *   Custom group object.
  * @param bool $force
  *   whether to force the deletion, even if there are custom fields.
  *
  * @return bool
  *   False if field exists for this group, true if group gets deleted.
  */
 public static function deleteGroup($group, $force = FALSE)
 {
     //check whether this contain any custom fields
     $customField = new CRM_Core_DAO_CustomField();
     $customField->custom_group_id = $group->id;
     $customField->find();
     // return early if there are custom fields and we're not
     // forcing the delete, otherwise delete the fields one by one
     while ($customField->fetch()) {
         if (!$force) {
             return FALSE;
         }
         CRM_Core_BAO_CustomField::deleteField($customField);
     }
     // drop the table associated with this custom group
     CRM_Core_BAO_SchemaHandler::dropTable($group->table_name);
     //delete  custom group
     $group->delete();
     CRM_Utils_Hook::post('delete', 'CustomGroup', $group->id, $group);
     return TRUE;
 }
 /**
  * Process the form when submitted
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_values['custom_group_id'], 'table_name');
     $singleValueOps = array('Text', 'Select', 'Radio', 'Autocomplete-Select');
     $mutliValueOps = array('CheckBox', 'Multi-Select', 'AdvMulti-Select');
     $srcHtmlType = $this->_values['html_type'];
     $dstHtmlType = $params['dst_html_type'];
     $customField = new CRM_Core_DAO_CustomField();
     $customField->id = $this->_id;
     $customField->find(TRUE);
     if ($dstHtmlType == 'Text' && in_array($srcHtmlType, array('Select', 'Radio', 'Autocomplete-Select'))) {
         $customField->option_group_id = "NULL";
         CRM_Core_BAO_CustomField::checkOptionGroup($this->_values['option_group_id']);
     }
     if (in_array($srcHtmlType, $mutliValueOps) && in_array($dstHtmlType, $singleValueOps)) {
         $this->flattenToFirstValue($tableName, $this->_values['column_name']);
     } elseif (in_array($srcHtmlType, $singleValueOps) && in_array($dstHtmlType, $mutliValueOps)) {
         $this->firstValueToFlatten($tableName, $this->_values['column_name']);
     }
     $customField->html_type = $dstHtmlType;
     $customField->save();
     // Reset cache for custom fields
     CRM_Core_BAO_Cache::deleteGroup('contact fields');
     CRM_Core_Session::setStatus(ts('Input type of custom field \'%1\' has been successfully changed to \'%2\'.', array(1 => $this->_values['label'], 2 => $dstHtmlType)));
 }
 /**
  * Process the form
  *
  * @param null
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // store the submitted values in an array
     $params = $this->controller->exportValues('Option');
     if ($this->_action == CRM_Core_Action::DELETE) {
         $fieldValues = array('option_group_id' => $this->_optionGroupID);
         $wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
         CRM_Core_BAO_CustomOption::del($this->_id);
         CRM_Core_Session::setStatus(ts('Your multiple choice option has been deleted'));
         return;
     }
     // set values for custom field properties and save
     $customOption = new CRM_Core_DAO_OptionValue();
     $customOption->label = $params['label'];
     $customOption->name = CRM_Utils_String::titleToVar($params['label']);
     $customOption->weight = $params['weight'];
     $customOption->value = $params['value'];
     $customOption->is_active = CRM_Utils_Array::value('is_active', $params, FALSE);
     $oldWeight = NULL;
     if ($this->_id) {
         $customOption->id = $this->_id;
         CRM_Core_BAO_CustomOption::updateCustomValues($params);
         $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'weight', 'id');
     }
     $fieldValues = array('option_group_id' => $this->_optionGroupID);
     $customOption->weight = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, $params['weight'], $fieldValues);
     $customOption->option_group_id = $this->_optionGroupID;
     $customField = new CRM_Core_DAO_CustomField();
     $customField->id = $this->_fid;
     if ($customField->find(TRUE) && ($customField->html_type == 'CheckBox' || $customField->html_type == 'AdvMulti-Select' || $customField->html_type == 'Multi-Select')) {
         $defVal = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($customField->default_value, 1, -1));
         if (CRM_Utils_Array::value('default_value', $params)) {
             if (!in_array($customOption->value, $defVal)) {
                 if (empty($defVal[0])) {
                     $defVal = array($customOption->value);
                 } else {
                     $defVal[] = $customOption->value;
                 }
                 $customField->default_value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $defVal) . CRM_Core_DAO::VALUE_SEPARATOR;
                 $customField->save();
             }
         } elseif (in_array($customOption->value, $defVal)) {
             $tempVal = array();
             foreach ($defVal as $v) {
                 if ($v != $customOption->value) {
                     $tempVal[] = $v;
                 }
             }
             $customField->default_value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $tempVal) . CRM_Core_DAO::VALUE_SEPARATOR;
             $customField->save();
         }
     } else {
         switch ($customField->data_type) {
             case 'Money':
                 $customOption->value = CRM_Utils_Rule::cleanMoney($customOption->value);
                 break;
             case 'Int':
                 $customOption->value = intval($customOption->value);
                 break;
             case 'Float':
                 $customOption->value = floatval($customOption->value);
                 break;
         }
         if (CRM_Utils_Array::value('default_value', $params)) {
             $customField->default_value = $customOption->value;
             $customField->save();
         } elseif ($customField->find(TRUE) && $customField->default_value == $customOption->value) {
             // this is the case where this option is the current default value and we have been reset
             $customField->default_value = 'null';
             $customField->save();
         }
     }
     $customOption->save();
     CRM_Core_Session::setStatus(ts('Your multiple choice option \'%1\' has been saved', array(1 => $customOption->label)));
     $buttonName = $this->controller->getButtonName();
     $session = CRM_Core_Session::singleton();
     if ($buttonName == $this->getButtonName('next', 'new')) {
         CRM_Core_Session::setStatus(ts(' You can add another option.'));
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field/option', 'reset=1&action=add&fid=' . $this->_fid . '&gid=' . $this->_gid));
     }
 }
/**
 * get 'custom field' 
 *
 * @param $params       array  Associative array of property name/value pairs to get custom field.
 *
 * @return  custom_field object
 *
 * @access public 
 *
 */
function crm_get_custom_field($params)
{
    _crm_initialize();
    if (!is_array($params)) {
        return _crm_error("params is not an array ");
    }
    $dao = new CRM_Core_DAO_CustomField();
    $dao->id = $params['id'];
    $dao->name = $params['name'];
    $dao->label = $params['label'];
    $dao->find(true);
    return $dao;
}
Example #18
0
 /**
  * adds $value['foo_display'] for each $value['foo'] enum from civicrm_custom_field
  *
  * @param array $values (reference)  the array up for enhancing
  * @return void
  */
 static function addDisplayEnums(&$values)
 {
     $enumFields =& CRM_Core_DAO_CustomField::getEnums();
     foreach ($enumFields as $enum) {
         if (isset($values[$enum])) {
             $values[$enum . '_display'] = CRM_Core_DAO_CustomField::tsEnum($enum, $values[$enum]);
         }
     }
 }
 /**
  * Validate custom data.
  *
  * @param array $params
  *   Custom data submitted.
  *   ie array( 'custom_1' => 'validate me' );
  *
  * @return array
  *   validation errors.
  */
 public static function validateCustomData($params)
 {
     $errors = array();
     if (!is_array($params) || empty($params)) {
         return $errors;
     }
     //pick up profile fields.
     $profileFields = array();
     $ufGroupId = CRM_Utils_Array::value('ufGroupId', $params);
     if ($ufGroupId) {
         $profileFields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
     }
     //lets start w/ params.
     foreach ($params as $key => $value) {
         $customFieldID = self::getKeyID($key);
         if (!$customFieldID) {
             continue;
         }
         //load the structural info for given field.
         $field = new CRM_Core_DAO_CustomField();
         $field->id = $customFieldID;
         if (!$field->find(TRUE)) {
             continue;
         }
         $dataType = $field->data_type;
         $profileField = CRM_Utils_Array::value($key, $profileFields, array());
         $fieldTitle = CRM_Utils_Array::value('title', $profileField);
         $isRequired = CRM_Utils_Array::value('is_required', $profileField);
         if (!$fieldTitle) {
             $fieldTitle = $field->label;
         }
         //no need to validate.
         if (CRM_Utils_System::isNull($value) && !$isRequired) {
             continue;
         }
         //lets validate first for required field.
         if ($isRequired && CRM_Utils_System::isNull($value)) {
             $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
             continue;
         }
         //now time to take care of custom field form rules.
         $ruleName = $errorMsg = NULL;
         switch ($dataType) {
             case 'Int':
                 $ruleName = 'integer';
                 $errorMsg = ts('%1 must be an integer (whole number).', array(1 => $fieldTitle));
                 break;
             case 'Money':
                 $ruleName = 'money';
                 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).', array(1 => $fieldTitle));
                 break;
             case 'Float':
                 $ruleName = 'numeric';
                 $errorMsg = ts('%1 must be a number (with or without decimal point).', array(1 => $fieldTitle));
                 break;
             case 'Link':
                 $ruleName = 'wikiURL';
                 $errorMsg = ts('%1 must be valid Website.', array(1 => $fieldTitle));
                 break;
         }
         if ($ruleName && !CRM_Utils_System::isNull($value)) {
             $valid = FALSE;
             $funName = "CRM_Utils_Rule::{$ruleName}";
             if (is_callable($funName)) {
                 $valid = call_user_func($funName, $value);
             }
             if (!$valid) {
                 $errors[$key] = $errorMsg;
             }
         }
     }
     return $errors;
 }
 /**
  * When changing the value of an option this is called to update all corresponding custom data
  *
  * @param int $optionId
  * @param string $newValue
  */
 public static function updateValue($optionId, $newValue)
 {
     $optionValue = new CRM_Core_DAO_OptionValue();
     $optionValue->id = $optionId;
     $optionValue->find(TRUE);
     $oldValue = $optionValue->value;
     if ($oldValue == $newValue) {
         return;
     }
     $customField = new CRM_Core_DAO_CustomField();
     $customField->option_group_id = $optionValue->option_group_id;
     $customField->find();
     while ($customField->fetch()) {
         $customGroup = new CRM_Core_DAO_CustomGroup();
         $customGroup->id = $customField->custom_group_id;
         $customGroup->find(TRUE);
         if (CRM_Core_BAO_CustomField::isSerialized($customField)) {
             $params = array(1 => array(CRM_Utils_Array::implodePadded($oldValue), 'String'), 2 => array(CRM_Utils_Array::implodePadded($newValue), 'String'), 3 => array('%' . CRM_Utils_Array::implodePadded($oldValue) . '%', 'String'));
         } else {
             $params = array(1 => array($oldValue, 'String'), 2 => array($newValue, 'String'), 3 => array($oldValue, 'String'));
         }
         $sql = "UPDATE `{$customGroup->table_name}` SET `{$customField->column_name}` = REPLACE(`{$customField->column_name}`, %1, %2) WHERE `{$customField->column_name}` LIKE %3";
         $customGroup->free();
         CRM_Core_DAO::executeQuery($sql, $params);
     }
     $customField->free();
 }
Example #21
0
 /**
  * Function to check the status of custom field used in uf fields
  *
  * @params  int $UFFieldId     uf field id 
  *
  * @return boolean   false if custom field are disabled else true
  * @static
  * @access public
  */
 static function checkUFStatus($UFFieldId)
 {
     $fieldName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFField', $UFFieldId, 'field_name');
     // return if field is not a custom field
     require_once 'CRM/Core/BAO/CustomField.php';
     if (!($customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldName))) {
         return true;
     }
     require_once "CRM/Core/DAO/CustomField.php";
     $customField = new CRM_Core_DAO_CustomField();
     $customField->id = $customFieldId;
     if ($customField->find(true)) {
         // if uf field is custom field
         if (!$customField->is_active) {
             return false;
         } else {
             return true;
         }
     }
 }