/** * @param CRM_Core_Form $form * * @throws Exception */ public static function preProcess(&$form) { if (empty($form->_caseId)) { CRM_Core_Error::fatal(ts('Case Id not found.')); } if (count($form->_caseId) != 1) { CRM_Core_Resources::fatal(ts('Expected one case-type')); } $caseId = CRM_Utils_Array::first($form->_caseId); $form->assign('clientID', $form->_currentlyViewedContactId); $form->assign('sortName', CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $form->_currentlyViewedContactId, 'sort_name')); $form->assign('caseTypeLabel', CRM_Case_BAO_Case::getCaseType($caseId)); // get the related cases for given case. $relatedCases = $form->get('relatedCases'); if (!isset($relatedCases)) { $relatedCases = CRM_Case_BAO_Case::getRelatedCases($caseId, $form->_currentlyViewedContactId); $form->set('relatedCases', empty($relatedCases) ? FALSE : $relatedCases); } }
/** * Set variables up before form is built. * * @param CRM_Core_Form $form * * @return void */ public static function preProcess(&$form) { $form->_addBlockName = CRM_Utils_Request::retrieve('block', 'String', CRM_Core_DAO::$_nullObject); $additionalblockCount = CRM_Utils_Request::retrieve('count', 'Positive', CRM_Core_DAO::$_nullObject); $form->assign('addBlock', FALSE); if ($form->_addBlockName && $additionalblockCount) { $form->assign('addBlock', TRUE); $form->assign('blockName', $form->_addBlockName); $form->assign('blockId', $additionalblockCount); $form->set($form->_addBlockName . '_Block_Count', $additionalblockCount); } if (is_a($form, 'CRM_Event_Form_ManageEvent_Location') || is_a($form, 'CRM_Contact_Form_Domain')) { $form->_blocks = array('Address' => ts('Address'), 'Email' => ts('Email'), 'Phone' => ts('Phone')); } $form->assign('blocks', $form->_blocks); $form->assign('className', CRM_Utils_System::getClassName($form)); // get address sequence. if (!($addressSequence = $form->get('addressSequence'))) { $addressSequence = CRM_Core_BAO_Address::addressSequence(); $form->set('addressSequence', $addressSequence); } $form->assign('addressSequence', $addressSequence); }
/** * @param CRM_Core_Form $form * * @throws Exception */ public static function preProcess(&$form) { if (!isset($form->_caseId)) { CRM_Core_Error::fatal(ts('Case Id not found.')); } if (count($form->_caseId) != 1) { CRM_Core_Resources::fatal(ts('Expected one case-type')); } $caseId = CRM_Utils_Array::first($form->_caseId); $form->assign('clientID', $form->_currentlyViewedContactId); $form->assign('caseTypeLabel', CRM_Case_BAO_Case::getCaseType($caseId)); // get the related cases for given case. $relatedCases = $form->get('relatedCases'); if (!isset($relatedCases)) { $relatedCases = CRM_Case_BAO_Case::getRelatedCases($caseId, $form->_currentlyViewedContactId); $form->set('relatedCases', empty($relatedCases) ? FALSE : $relatedCases); } $excludeCaseIds = array($caseId); if (is_array($relatedCases) && !empty($relatedCases)) { $excludeCaseIds = array_merge($excludeCaseIds, array_keys($relatedCases)); } $form->assign('excludeCaseIds', implode(',', $excludeCaseIds)); }
/** * Global form rule. * * @param array $fields * The input form values. * @param array $files * The uploaded files if any. * @param CRM_Core_Form $self * * @return bool|array * true if no errors, else array of errors */ public static function formRule($fields, $files, $self) { $errors = array(); $amount = self::computeAmount($fields, $self->_values); if (CRM_Utils_Array::value('auto_renew', $fields) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) { $errors['auto_renew'] = ts('You cannot have auto-renewal on if you are paying later.'); } if (!empty($fields['selectMembership']) && $fields['selectMembership'] != 'no_thanks' || !empty($fields['priceSetId']) && $self->_useForMember) { $isTest = $self->_action & CRM_Core_Action::PREVIEW ? TRUE : FALSE; $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, $isTest, TRUE); $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(); $unallowedOrgs = array(); foreach (array_keys($lifeMember) as $memTypeId) { $unallowedOrgs[] = $membershipOrgDetails[$memTypeId]; } } //check for atleast one pricefields should be selected if (!empty($fields['priceSetId']) && empty($self->_ccid)) { $priceField = new CRM_Price_DAO_PriceField(); $priceField->price_set_id = $fields['priceSetId']; $priceField->orderBy('weight'); $priceField->find(); $check = array(); $membershipIsActive = TRUE; $previousId = $otherAmount = FALSE; while ($priceField->fetch()) { if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) { $previousId = $priceField->id; if ($priceField->name == 'membership_amount' && !$priceField->is_active) { $membershipIsActive = FALSE; } } if ($priceField->name == 'other_amount') { if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) && array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])) { $otherAmount = $priceField->id; } elseif (!empty($fields["price_{$priceField->id}"])) { $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]); $min = CRM_Utils_Array::value('min_amount', $self->_values); $max = CRM_Utils_Array::value('max_amount', $self->_values); if ($min && $otherAmountVal < $min) { $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1', array(1 => $min)); } if ($max && $otherAmountVal > $max) { $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.', array(1 => $max)); } } } if (!empty($fields["price_{$priceField->id}"]) || $previousId == $priceField->id && isset($fields["price_{$previousId}"]) && empty($fields["price_{$previousId}"])) { $check[] = $priceField->id; } } $currentMemberships = NULL; if ($membershipIsActive) { $is_test = $self->_mode != 'live' ? 1 : 0; $memContactID = $self->_membershipContactID; // For anonymous user check using dedupe rule // if user has Cancelled Membership if (!$memContactID) { $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual'); $dedupeParams['check_permission'] = FALSE; $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual'); // if we find more than one contact, use the first one $memContactID = CRM_Utils_Array::value(0, $ids); } $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID, $is_test); $errorText = 'Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.'; foreach ($self->_values['fee'] as $fieldKey => $fieldValue) { if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) { if (!is_array($fields['price_' . $fieldKey]) && isset($fieldValue['options'][$fields['price_' . $fieldKey]])) { if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]]) && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)) { $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id']))); } } else { if (is_array($fields['price_' . $fieldKey])) { foreach (array_keys($fields['price_' . $fieldKey]) as $key) { if (array_key_exists('membership_type_id', $fieldValue['options'][$key]) && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)) { $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id']))); } } } } } } } // CRM-12233 if ($membershipIsActive && !$self->_membershipBlock['is_required'] && $self->_values['amount_block_is_active']) { $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL; foreach ($self->_values['fee'] as $fieldKey => $fieldValue) { // if 'No thank you' membership is selected then set $membershipFieldId if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) { $membershipFieldId = $fieldKey; } elseif ($membershipFieldId) { if ($fieldValue['name'] == 'other_amount') { $otherFieldId = $fieldKey; } elseif ($fieldValue['name'] == 'contribution_amount') { $contributionFieldId = $fieldKey; } if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') { $errorKey = $fieldKey; } } } // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) { $errors["price_{$errorKey}"] = ts('Additional Contribution is required.'); } } if (empty($check) && empty($self->_ccid)) { if ($self->_useForMember == 1 && $membershipIsActive) { $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).'); } else { $errors['_qf_default'] = ts('Select at least one option from Contribution(s).'); } } if ($otherAmount && !empty($check)) { $errors["price_{$otherAmount}"] = ts('Amount is required field.'); } if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) { $priceFieldIDS = array(); $priceFieldMemTypes = array(); foreach ($self->_priceSet['fields'] as $priceId => $value) { if (!empty($fields['price_' . $priceId]) || $self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required'])) { if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) { foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) { if ($isSet) { $priceFieldIDS[] = $priceFldVal; } } } elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) { // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577 $priceFieldIDS[] = $fields['price_' . $priceId]; } if (!empty($value['options'])) { foreach ($value['options'] as $val) { if (!empty($val['membership_type_id']) && ($fields['price_' . $priceId] == $val['id'] || isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))) { $priceFieldMemTypes[] = $val['membership_type_id']; } } } } } if (!empty($lifeMember)) { foreach ($priceFieldIDS as $priceFieldId) { if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) && in_array($membershipOrgDetails[$id], $unallowedOrgs)) { $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.'); break; } } } if (!empty($priceFieldIDS)) { $ids = implode(',', $priceFieldIDS); $priceFieldIDS['id'] = $fields['priceSetId']; $self->set('memberPriceFieldIDS', $priceFieldIDS); $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids); foreach ($count as $id => $occurrence) { if ($occurrence > 1) { $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.'); } } } if (empty($priceFieldMemTypes) && $self->_membershipBlock['is_required'] == 1) { $errors['_qf_default'] = ts('Please select at least one membership option.'); } } CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem); if ($fields['amount'] < 0) { $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly'); } $amount = $fields['amount']; } if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks') { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $fields['selectProduct']; $productDAO->find(TRUE); $min_amount = $productDAO->min_contribution; if ($amount < $min_amount) { $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount))); CRM_Core_Session::setStatus($errors['selectProduct']); } } //CRM-16285 - Function to handle validation errors on form, for recurring contribution field. CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors); if (!empty($fields['is_recur']) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) { $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.'); } // validate PCP fields - if not anonymous, we need a nick name value if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') { $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.'); } // return if this is express mode $config = CRM_Core_Config::singleton(); if ($self->_paymentProcessor && $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) { if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) { return $errors; } } //validate the pledge fields. if (!empty($self->_values['pledge_block_id'])) { //validation for pledge payment. if (!empty($self->_values['pledge_id'])) { if (empty($fields['pledge_amount'])) { $errors['pledge_amount'] = ts('At least one payment option needs to be checked.'); } } elseif (!empty($fields['is_pledge'])) { if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) { $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.'); } else { if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) { $errors['pledge_installments'] = ts('Pledge Installments is required field.'); } elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 1) { $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.'); } elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 0) { $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.'); } } //validation for Pledge Frequency Interval. if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) { $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.'); } else { if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) { $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.'); } elseif (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == 0) { $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0'); } } } } // if the user has chosen a free membership or the amount is less than zero // i.e. we don't need to validate payment related fields or profiles. if ((double) $amount <= 0.0) { return $errors; } if (CRM_Utils_Array::value('payment_processor_id', $fields) == NULL) { $errors['payment_processor_id'] = ts('Payment Method is a required field.'); } else { CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, !$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing'); } foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) { $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name'); if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) { $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting)))); } } } return empty($errors) ? TRUE : $errors; }
/** * Process the form submission. * * @param array $params * @param string $db * @param \CRM_Core_Form $form */ public function postProcess(&$params, &$db, &$form) { $importJob = new CRM_Contact_Import_ImportJob(CRM_Utils_Array::value('import_table_name', $params), $params['sqlQuery'], TRUE); $form->set('importTableName', $importJob->getTableName()); }
/** * Get the result of the search for Add to * forms. * * @param CRM_Core_Form $form * @param array $params * This contains elements for search criteria. */ public function search(&$form, &$params) { //max records that will be listed $searchValues = array(); if (!empty($params['rel_contact'])) { if (isset($params['rel_contact_id']) && is_numeric($params['rel_contact_id'])) { $searchValues[] = array('contact_id', '=', $params['rel_contact_id'], 0, 1); } else { $searchValues[] = array('sort_name', 'LIKE', $params['rel_contact'], 0, 1); } } $contactTypeAdded = FALSE; $excludedContactIds = array(); if (isset($form->_contactId)) { $excludedContactIds[] = $form->_contactId; } if (!empty($params['relationship_type_id'])) { $relationshipType = new CRM_Contact_DAO_RelationshipType(); list($rid, $direction) = explode('_', $params['relationship_type_id'], 2); $relationshipType->id = $rid; if ($relationshipType->find(TRUE)) { if ($direction == 'a_b') { $type = $relationshipType->contact_type_b; $subType = $relationshipType->contact_sub_type_b; } else { $type = $relationshipType->contact_type_a; $subType = $relationshipType->contact_sub_type_a; } $form->set('contact_type', $type); $form->set('contact_sub_type', $subType); if ($type == 'Individual' || $type == 'Organization' || $type == 'Household') { $searchValues[] = array('contact_type', '=', $type, 0, 0); $contactTypeAdded = TRUE; } if ($subType) { $searchValues[] = array('contact_sub_type', '=', $subType, 0, 0); } } } if (!$contactTypeAdded && !empty($params['contact_type'])) { $searchValues[] = array('contact_type', '=', $params['contact_type'], 0, 0); } // get the count of contact $contactBAO = new CRM_Contact_BAO_Contact(); $query = new CRM_Contact_BAO_Query($searchValues); $searchCount = $query->searchQuery(0, 0, NULL, TRUE); $form->set('searchCount', $searchCount); if ($searchCount <= 50) { // get the result of the search $result = $query->searchQuery(0, 50, NULL); $config = CRM_Core_Config::singleton(); $searchRows = array(); //variable is set if only one record is foun and that record already has relationship with the contact $duplicateRelationship = 0; while ($result->fetch()) { $query->convertToPseudoNames($result); $contactID = $result->contact_id; if (in_array($contactID, $excludedContactIds)) { $duplicateRelationship++; continue; } $duplicateRelationship = 0; $searchRows[$contactID]['id'] = $contactID; $searchRows[$contactID]['name'] = $result->sort_name; $searchRows[$contactID]['city'] = $result->city; $searchRows[$contactID]['state'] = $result->state_province; $searchRows[$contactID]['email'] = $result->email; $searchRows[$contactID]['phone'] = $result->phone; $contact_type = '<img src="' . $config->resourceBase . 'i/contact_'; $searchRows[$contactID]['type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type); } $form->set('searchRows', $searchRows); $form->set('duplicateRelationship', $duplicateRelationship); } else { // resetting the session variables if many records are found $form->set('searchRows', NULL); $form->set('duplicateRelationship', NULL); } }
/** * Post process function. * * @param CRM_Core_Form $form * @param bool $redirect */ public static function postProcess(&$form, $redirect = TRUE) { $params = $form->getVar('_params'); $instanceID = $form->getVar('_id'); if ($isNew = $form->getVar('_createNew')) { // set the report_id since base template is going to be same, and we going to unset $instanceID // which will make it difficult later on, to compute report_id $params['report_id'] = CRM_Report_Utils_Report::getValueFromUrl($instanceID); // Unset $instanceID so a new copy would be created. $instanceID = NULL; } $params['instance_id'] = $instanceID; if (!empty($params['is_navigation'])) { $params['navigation'] = $form->_navigation; } elseif ($instanceID) { // Delete navigation if exists. $navId = CRM_Core_DAO::getFieldValue('CRM_Report_DAO_ReportInstance', $instanceID, 'navigation_id', 'id'); if ($navId) { CRM_Core_BAO_Navigation::processDelete($navId); CRM_Core_BAO_Navigation::resetNavigation(); } } // make a copy of params $formValues = $params; // unset params from $formValues that doesn't match with DB columns of instance tables, and also not required in form-values for sure $unsetFields = array('title', 'to_emails', 'cc_emails', 'header', 'footer', 'qfKey', 'id', '_qf_default', 'report_header', 'report_footer', 'grouprole'); foreach ($unsetFields as $field) { unset($formValues[$field]); } $view_mode = $formValues['view_mode']; // pass form_values as string $params['form_values'] = serialize($formValues); $instance = CRM_Report_BAO_ReportInstance::create($params); $form->set('id', $instance->id); if ($instanceID && !$isNew) { // updating existing instance $statusMsg = ts('"%1" report has been updated.', array(1 => $instance->title)); } elseif ($form->getVar('_id') && $isNew) { $statusMsg = ts('Your report has been successfully copied as "%1". You are currently viewing the new copy.', array(1 => $instance->title)); } else { $statusMsg = ts('"%1" report has been successfully created. You are currently viewing the new report instance.', array(1 => $instance->title)); } CRM_Core_Session::setStatus($statusMsg); if ($redirect) { $urlParams = array('reset' => 1); if ($view_mode == 'view') { $urlParams['force'] = 1; } else { $urlParams['output'] = 'criteria'; } CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/report/instance/{$instance->id}", $urlParams)); } }
/** * Assign Profiles. * * @param CRM_Core_Form $form */ public static function assignProfiles(&$form) { $participantParams = $form->_params; $formattedValues = $profileFields = array(); $count = 1; foreach ($participantParams as $participantNum => $participantValue) { if ($participantNum) { $prefix1 = 'additional'; $prefix2 = 'additional_'; } else { $prefix1 = ''; $prefix2 = ''; } if ($participantValue != 'skip') { //get the customPre profile info if (!empty($form->_values[$prefix2 . 'custom_pre_id'])) { $values = $groupName = array(); CRM_Event_BAO_Event::displayProfile($participantValue, $form->_values[$prefix2 . 'custom_pre_id'], $groupName, $values, $profileFields); if (count($values)) { $formattedValues[$count][$prefix1 . 'CustomPre'] = $values; } $formattedValues[$count][$prefix1 . 'CustomPreGroupTitle'] = CRM_Utils_Array::value('groupTitle', $groupName); } //get the customPost profile info if (!empty($form->_values[$prefix2 . 'custom_post_id'])) { $values = $groupName = array(); foreach ($form->_values[$prefix2 . 'custom_post_id'] as $gids) { $val = array(); CRM_Event_BAO_Event::displayProfile($participantValue, $gids, $group, $val, $profileFields); $values[$gids] = $val; $groupName[$gids] = $group; } if (count($values)) { $formattedValues[$count][$prefix1 . 'CustomPost'] = $values; } if (isset($formattedValues[$count][$prefix1 . 'CustomPre'])) { $formattedValues[$count][$prefix1 . 'CustomPost'] = array_diff_assoc($formattedValues[$count][$prefix1 . 'CustomPost'], $formattedValues[$count][$prefix1 . 'CustomPre']); } $formattedValues[$count][$prefix1 . 'CustomPostGroupTitle'] = $groupName; } $count++; } $form->_fields = $profileFields; } if (!empty($formattedValues)) { $form->assign('primaryParticipantProfile', $formattedValues[1]); $form->set('primaryParticipantProfile', $formattedValues[1]); if ($count > 2) { unset($formattedValues[1]); $form->assign('addParticipantProfile', $formattedValues); $form->set('addParticipantProfile', $formattedValues); } } }
/** * Build the mapping form. * * @param CRM_Core_Form $form * @param string $mappingType * (Export/Import/Search Builder). * @param int $mappingId * @param int $columnNo * @param int $blockCount * (no of blocks shown). * @param NULL $exportMode * * @return void */ public static function buildMappingForm(&$form, $mappingType = 'Export', $mappingId = NULL, $columnNo, $blockCount = 3, $exportMode = NULL) { if ($mappingType == 'Export') { $name = "Map"; $columnCount = array('1' => $columnNo); } elseif ($mappingType == 'Search Builder') { $name = "Builder"; $columnCount = $columnNo; } //get the saved mapping details if ($mappingType == 'Export') { $form->applyFilter('saveMappingName', 'trim'); //to save the current mappings if (!isset($mappingId)) { $saveDetailsName = ts('Save this field mapping'); $form->add('text', 'saveMappingName', ts('Name')); $form->add('text', 'saveMappingDesc', ts('Description')); } else { $form->assign('loadedMapping', $mappingId); $params = array('id' => $mappingId); $temp = array(); $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp); $form->assign('savedName', $mappingDetails->name); $form->add('hidden', 'mappingId', $mappingId); $form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL); $saveDetailsName = ts('Save as a new field mapping'); $form->add('text', 'saveMappingName', ts('Name')); $form->add('text', 'saveMappingDesc', ts('Description')); } $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)")); $form->addFormRule(array('CRM_Export_Form_Map', 'formRule'), $form->get('mappingTypeId')); } elseif ($mappingType == 'Search Builder') { $form->addElement('submit', 'addBlock', ts('Also include contacts where'), array('class' => 'submit-link')); } $defaults = array(); $hasLocationTypes = array(); $hasRelationTypes = array(); $fields = array(); if ($mappingType == 'Export') { $required = TRUE; } elseif ($mappingType == 'Search Builder') { $required = FALSE; } $contactType = array('Individual', 'Household', 'Organization'); foreach ($contactType as $value) { $contactFields = CRM_Contact_BAO_Contact::exportableFields($value, FALSE, $required); $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields()); // exclude the address options disabled in the Address Settings $fields[$value] = CRM_Core_BAO_Address::validateAddressOptions($contactFields); ksort($fields[$value]); if ($mappingType == 'Export') { $relationships = array(); $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $value); asort($relationshipTypes); foreach ($relationshipTypes as $key => $var) { list($type) = explode('_', $key); $relationships[$key]['title'] = $var; $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/'; $relationships[$key]['export'] = TRUE; $relationships[$key]['relationship_type_id'] = $type; $relationships[$key]['related'] = TRUE; $relationships[$key]['hasRelationType'] = 1; } if (!empty($relationships)) { $fields[$value] = array_merge($fields[$value], array('related' => array('title' => ts('- related contact info -'))), $relationships); } } } //get the current employer for mapping. if ($required) { $fields['Individual']['current_employer']['title'] = ts('Current Employer'); } // add component fields $compArray = array(); //we need to unset groups, tags, notes for component export if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) { foreach (array('groups', 'tags', 'notes') as $value) { unset($fields['Individual'][$value]); unset($fields['Household'][$value]); unset($fields['Organization'][$value]); } } if ($mappingType == 'Search Builder') { //build the common contact fields array. $fields['Contact'] = array(); foreach ($fields['Individual'] as $key => $value) { if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) { $fields['Contact'][$key] = $value; unset($fields['Organization'][$key], $fields['Household'][$key], $fields['Individual'][$key]); } } if (array_key_exists('note', $fields['Contact'])) { $noteTitle = $fields['Contact']['note']['title']; $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject'); $fields['Contact']['note_body'] = array('title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'); $fields['Contact']['note_subject'] = array('title' => $noteTitle . ': ' . ts('Subject Only'), 'name' => 'note_subject'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) { if (CRM_Core_Permission::access('CiviContribute')) { $fields['Contribution'] = CRM_Contribute_BAO_Contribution::exportableFields(); foreach (array('contribution_contact_id', 'contribution_soft_credit_name', 'contribution_soft_credit_amount', 'contribution_soft_credit_type', 'contribution_soft_credit_contribution_id') as $element) { unset($fields['Contribution'][$element]); } $compArray['Contribution'] = ts('Contribution'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { if (CRM_Core_Permission::access('CiviEvent')) { $fields['Participant'] = CRM_Event_BAO_Participant::exportableFields(); //get the component payment fields if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { $componentPaymentFields = array(); foreach (CRM_Export_BAO_Export::componentPaymentFields() as $payField => $payTitle) { $componentPaymentFields[$payField] = array('title' => $payTitle); } $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields); } $compArray['Participant'] = ts('Participant'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { if (CRM_Core_Permission::access('CiviMember')) { $fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode); unset($fields['Membership']['membership_contact_id']); $compArray['Membership'] = ts('Membership'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { if (CRM_Core_Permission::access('CiviPledge')) { $fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields(); unset($fields['Pledge']['pledge_contact_id']); $compArray['Pledge'] = ts('Pledge'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::CASE_EXPORT) { if (CRM_Core_Permission::access('CiviCase')) { $fields['Case'] = CRM_Case_BAO_Case::exportableFields(); $compArray['Case'] = ts('Case'); $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case'); $compArray['Activity'] = ts('Case Activity'); unset($fields['Case']['case_contact_id']); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::GRANT_EXPORT) { if (CRM_Core_Permission::access('CiviGrant')) { $fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields(); unset($fields['Grant']['grant_contact_id']); if ($mappingType == 'Search Builder') { unset($fields['Grant']['grant_type_id']); } $compArray['Grant'] = ts('Grant'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity'); $compArray['Activity'] = ts('Activity'); } //Contact Sub Type For export $contactSubTypes = array(); $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); foreach ($subTypes as $subType => $val) { //adding subtype specific relationships CRM-5256 $csRelationships = array(); if ($mappingType == 'Export') { $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'], FALSE, 'label', TRUE, $subType); foreach ($subTypeRelationshipTypes as $key => $var) { if (!array_key_exists($key, $fields[$val['parent']])) { list($type) = explode('_', $key); $csRelationships[$key]['title'] = $var; $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/'; $csRelationships[$key]['export'] = TRUE; $csRelationships[$key]['relationship_type_id'] = $type; $csRelationships[$key]['related'] = TRUE; $csRelationships[$key]['hasRelationType'] = 1; } } } $fields[$subType] = $fields[$val['parent']] + $csRelationships; //custom fields for sub type $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType); $fields[$subType] += $subTypeFields; if (!empty($subTypeFields) || !empty($csRelationships)) { $contactSubTypes[$subType] = $val['label']; } } unset($subTypes); foreach ($fields as $key => $value) { foreach ($value as $key1 => $value1) { //CRM-2676, replacing the conflict for same custom field name from different custom group. $customGroupName = self::getCustomGroupName($key1); if ($customGroupName) { $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title']; } else { $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title']; } if (isset($value1['hasLocationType'])) { $hasLocationTypes[$key][$key1] = $value1['hasLocationType']; } if (isset($value1['hasRelationType'])) { $hasRelationTypes[$key][$key1] = $value1['hasRelationType']; unset($relatedMapperFields[$key][$key1]); } } if (array_key_exists('related', $relatedMapperFields[$key])) { unset($relatedMapperFields[$key]['related']); } } $mapperKeys = array_keys($mapperFields); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); // FIXME: dirty hack to make the default option show up first. This // avoids a mozilla browser bug with defaults on dynamically constructed // selector widgets. if ($defaultLocationType) { $defaultLocation = $locationTypes[$defaultLocationType->id]; unset($locationTypes[$defaultLocationType->id]); $locationTypes = array($defaultLocationType->id => $defaultLocation) + $locationTypes; } $locationTypes = array(' ' => ts('Primary')) + $locationTypes; // since we need a hierarchical list to display contact types & subtypes, // this is what we going to display in first selector $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE); if ($mappingType == 'Search Builder') { $contactTypes = array('Contact' => ts('Contacts')) + $contactTypes; } $sel1 = array('' => ts('- select record type -')) + $contactTypes + $compArray; foreach ($sel1 as $key => $sel) { if ($key) { // sort everything BUT the contactType which is sorted seperately by // an initial commit of CRM-13278 (check ksort above) if (!in_array($key, $contactType)) { asort($mapperFields[$key]); } $sel2[$key] = array('' => ts('- select field -')) + $mapperFields[$key]; } } $sel3[''] = NULL; $sel5[''] = NULL; $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); asort($phoneTypes); foreach ($sel1 as $k => $sel) { if ($k) { foreach ($locationTypes as $key => $value) { if (trim($key) != '') { $sel4[$k]['phone'][$key] =& $phoneTypes; $sel4[$k]['im'][$key] =& $imProviders; } } } } foreach ($sel1 as $k => $sel) { if ($k) { foreach ($mapperFields[$k] as $key => $value) { if (isset($hasLocationTypes[$k][$key])) { $sel3[$k][$key] = $locationTypes; } else { $sel3[$key] = NULL; } } } } // Array for core fields and relationship custom data $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE); if ($mappingType == 'Export') { foreach ($sel1 as $k => $sel) { if ($k) { foreach ($mapperFields[$k] as $field => $dontCare) { if (isset($hasRelationTypes[$k][$field])) { list($id, $first, $second) = explode('_', $field); // FIX ME: For now let's not expose custom data related to relationship $relationshipCustomFields = array(); //$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id ); //asort($relationshipCustomFields); $relationshipType = new CRM_Contact_BAO_RelationshipType(); $relationshipType->id = $id; if ($relationshipType->find(TRUE)) { $direction = "contact_sub_type_{$second}"; if (isset($relationshipType->{$direction})) { $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->{$direction}], (array) $relationshipCustomFields); } else { $target_type = 'contact_type_' . $second; $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->{$target_type}], (array) $relationshipCustomFields); } } $relationshipType->free(); asort($relatedFields); $sel5[$k][$field] = $relatedFields; } } } } //Location Type for relationship fields foreach ($sel5 as $k => $v) { if ($v) { foreach ($v as $rel => $fields) { foreach ($fields as $field => $fieldLabel) { if (isset($hasLocationTypes[$k][$field])) { $sel6[$k][$rel][$field] = $locationTypes; } } } } } //PhoneTypes for relationship fields $sel7[''] = NULL; foreach ($sel6 as $k => $rel) { if ($k) { foreach ($rel as $phonekey => $phonevalue) { foreach ($locationTypes as $locType => $loc) { if (trim($locType) != '') { $sel7[$k][$phonekey]['phone'][$locType] =& $phoneTypes; $sel7[$k][$phonekey]['im'][$locType] =& $imProviders; } } } } } } //special fields that have location, hack for primary location $specialFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im'); if (isset($mappingId)) { $colCnt = 0; list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue) = CRM_Core_BAO_Mapping::getMappingFields($mappingId); $blkCnt = count($mappingName); if ($blkCnt >= $blockCount) { $blockCount = $blkCnt + 1; } for ($x = 1; $x < $blockCount; $x++) { if (isset($mappingName[$x])) { $colCnt = count($mappingName[$x]); if ($colCnt >= $columnCount[$x]) { $columnCount[$x] = $colCnt; } } } } $form->_blockCount = $blockCount; $form->_columnCount = $columnCount; $form->set('blockCount', $form->_blockCount); $form->set('columnCount', $form->_columnCount); $defaults = $noneArray = $nullArray = array(); //used to warn for mismatch column count or mismatch mapping $warning = 0; for ($x = 1; $x < $blockCount; $x++) { for ($i = 0; $i < $columnCount[$x]; $i++) { $sel =& $form->addElement('hierselect', "mapper[{$x}][{$i}]", ts('Mapper for Field %1', array(1 => $i)), NULL); $jsSet = FALSE; if (isset($mappingId)) { $locationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0; if (isset($mappingName[$x][$i])) { if (is_array($mapperFields[$mappingContactType[$x][$i]])) { if (isset($mappingRelation[$x][$i])) { $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$x][$i])); $relLocationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0; if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) { $relLocationId = " "; } $relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL; $defaults["mapper[{$x}][{$i}]"] = array($mappingContactType[$x][$i], $mappingRelation[$x][$i], $locationId, $phoneType, $mappingName[$x][$i], $relLocationId, $relPhoneType); if (!$locationId) { $noneArray[] = array($x, $i, 2); } if (!$phoneType && !$imProvider) { $noneArray[] = array($x, $i, 3); } if (!$mappingName[$x][$i]) { $noneArray[] = array($x, $i, 4); } if (!$relLocationId) { $noneArray[] = array($x, $i, 5); } if (!$relPhoneType) { $noneArray[] = array($x, $i, 6); } $noneArray[] = array($x, $i, 2); } else { $phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL; $imProvider = isset($mappingImProvider[$x][$i]) ? $mappingImProvider[$x][$i] : NULL; if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) { $locationId = " "; } $defaults["mapper[{$x}][{$i}]"] = array($mappingContactType[$x][$i], $mappingName[$x][$i], $locationId, $phoneType); if (!$mappingName[$x][$i]) { $noneArray[] = array($x, $i, 1); } if (!$locationId) { $noneArray[] = array($x, $i, 2); } if (!$phoneType && !$imProvider) { $noneArray[] = array($x, $i, 3); } $noneArray[] = array($x, $i, 4); $noneArray[] = array($x, $i, 5); $noneArray[] = array($x, $i, 6); } $jsSet = TRUE; if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) { $defaults["operator[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]); } if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) { $defaults["value[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingValue[$x]); } } } } //Fix for Search Builder if ($mappingType == 'Export') { $j = 7; } else { $j = 4; } $formValues = $form->exportValues(); if (!$jsSet) { if (empty($formValues)) { // Incremented length for third select box(relationship type) for ($k = 1; $k < $j; $k++) { $noneArray[] = array($x, $i, $k); } } else { if (!empty($formValues['mapper'][$x])) { foreach ($formValues['mapper'][$x] as $value) { for ($k = 1; $k < $j; $k++) { if (!isset($formValues['mapper'][$x][$i][$k]) || !$formValues['mapper'][$x][$i][$k]) { $noneArray[] = array($x, $i, $k); } else { $nullArray[] = array($x, $i, $k); } } } } else { for ($k = 1; $k < $j; $k++) { $noneArray[] = array($x, $i, $k); } } } } //Fix for Search Builder if ($mappingType == 'Export') { if (!isset($mappingId) || $i >= count(reset($mappingName))) { if (isset($formValues['mapper']) && isset($formValues['mapper'][$x][$i][1]) && array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)) { $sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4)); } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7)); } } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7)); } } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4)); } if ($mappingType == 'Search Builder') { //CRM -2292, restricted array set $operatorArray = array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators(); $form->add('select', "operator[{$x}][{$i}]", '', $operatorArray); $form->add('text', "value[{$x}][{$i}]", ''); } } //end of columnCnt for if ($mappingType == 'Search Builder') { $title = ts('Another search field'); } else { $title = ts('Select more fields'); } $form->addElement('submit', "addMore[{$x}]", $title, array('class' => 'submit-link')); } //end of block for $js = "<script type='text/javascript'>\n"; $formName = "document.{$name}"; if (!empty($nullArray)) { $js .= "var nullArray = ["; $elements = array(); $seen = array(); foreach ($nullArray as $element) { $key = "{$element[0]}, {$element[1]}, {$element[2]}"; if (!isset($seen[$key])) { $elements[] = "[{$key}]"; $seen[$key] = 1; } } $js .= implode(', ', $elements); $js .= "]"; $js .= "\n for (var i=0;i<nullArray.length;i++) {\n if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {\n {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';\n }\n }\n"; } if (!empty($noneArray)) { $js .= "var noneArray = ["; $elements = array(); $seen = array(); foreach ($noneArray as $element) { $key = "{$element[0]}, {$element[1]}, {$element[2]}"; if (!isset($seen[$key])) { $elements[] = "[{$key}]"; $seen[$key] = 1; } } $js .= implode(', ', $elements); $js .= "]"; $js .= "\n for (var i=0;i<noneArray.length;i++) {\n if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {\n {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';\n }\n }\n"; } $js .= "</script>\n"; $form->assign('initHideBoxes', $js); $form->assign('columnCount', $columnCount); $form->assign('blockCount', $blockCount); $form->setDefaults($defaults); $form->setDefaultAction('refresh'); }
/** * Update contact fields. * * @param int $contactID * @param array $params * @param $fields * @param CRM_Core_Form $form * * @return void */ public static function updateContactFields($contactID, $params, $fields, &$form) { //add the contact to group, if add to group is selected for a //particular uf group // get the add to groups $addToGroups = array(); if (!empty($form->_fields)) { foreach ($form->_fields as $key => $value) { if (!empty($value['add_to_group_id'])) { $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id']; } } } // check for profile double opt-in and get groups to be subscribed $subscribeGroupIds = CRM_Core_BAO_UFGroup::getDoubleOptInGroupIds($params, $contactID); foreach ($addToGroups as $k) { if (array_key_exists($k, $subscribeGroupIds)) { unset($addToGroups[$k]); } } // since we are directly adding contact to group lets unset it from mailing if (!empty($addToGroups)) { foreach ($addToGroups as $groupId) { if (isset($subscribeGroupIds[$groupId])) { unset($subscribeGroupIds[$groupId]); } } } if ($contactID) { $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type'); if (array_key_exists('contact_id', $params) && empty($params['contact_id'])) { // we unset this here because the downstream function ignores the contactID we give it // if it is set & it is difficult to understand the implications of 'fixing' this downstream // but if we are passing a contact id into this function it's reasonable to assume we don't // want it ignored unset($params['contact_id']); } $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $contactID, $addToGroups, NULL, $ctype, TRUE); } else { foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { if (!isset($params[$greeting . '_id'])) { $params[$greeting . '_id'] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting); } } $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, NULL, $addToGroups, NULL, NULL, TRUE); $form->set('contactID', $contactID); } //get email primary first if exist $subscribtionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params)); if (!$subscribtionEmail['email']) { $subscribtionEmail['email'] = CRM_Utils_Array::value("email-{$form->_bltID}", $params); } // subscribing contact to groups if (!empty($subscribeGroupIds) && $subscribtionEmail['email']) { CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($subscribeGroupIds, $subscribtionEmail, $contactID); } return $contactID; }
/** * @param CRM_Core_Form $form * @param int $timeout */ public function runImport(&$form, $timeout = 55) { $mapper = $this->_mapper; $mapperFields = array(); $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); //initialize mapper perperty value. $mapperPeroperties = array('mapperRelated' => 'mapperRelatedVal', 'mapperLocTypes' => 'mapperLocTypesVal', 'mapperPhoneTypes' => 'mapperPhoneTypesVal', 'mapperImProviders' => 'mapperImProvidersVal', 'mapperWebsiteTypes' => 'mapperWebsiteTypesVal', 'mapperRelatedContactType' => 'mapperRelatedContactTypeVal', 'mapperRelatedContactDetails' => 'mapperRelatedContactDetailsVal', 'mapperRelatedContactLocType' => 'mapperRelatedContactLocTypeVal', 'mapperRelatedContactPhoneType' => 'mapperRelatedContactPhoneTypeVal', 'mapperRelatedContactImProvider' => 'mapperRelatedContactImProviderVal', 'mapperRelatedContactWebsiteType' => 'mapperRelatedContactWebsiteTypeVal'); foreach ($mapper as $key => $value) { //set respective mapper value to null. foreach (array_values($mapperPeroperties) as $perpertyVal) { ${$perpertyVal} = NULL; } $fldName = CRM_Utils_Array::value(0, $mapper[$key]); $header = array($this->_mapFields[$fldName]); $selOne = CRM_Utils_Array::value(1, $mapper[$key]); $selTwo = CRM_Utils_Array::value(2, $mapper[$key]); $selThree = CRM_Utils_Array::value(3, $mapper[$key]); $this->_mapperKeys[$key] = $fldName; //need to differentiate non location elements. if ($selOne && is_numeric($selOne)) { if ($fldName == 'url') { $header[] = $websiteTypes[$selOne]; $mapperWebsiteTypesVal = $selOne; } else { $header[] = $locationTypes[$selOne]; $mapperLocTypesVal = $selOne; if ($selTwo && is_numeric($selTwo)) { if ($fldName == 'phone') { $header[] = $phoneTypes[$selTwo]; $mapperPhoneTypesVal = $selTwo; } elseif ($fldName == 'im') { $header[] = $imProviders[$selTwo]; $mapperImProvidersVal = $selTwo; } } } } $fldNameParts = explode('_', $fldName, 3); $id = $fldNameParts[0]; $first = isset($fldNameParts[1]) ? $fldNameParts[1] : NULL; $second = isset($fldNameParts[2]) ? $fldNameParts[2] : NULL; if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $header[] = ucwords(str_replace("_", " ", $selOne)); $relationType = new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(TRUE); $mapperRelatedContactTypeVal = $relationType->{"contact_type_{$second}"}; $mapperRelatedVal = $fldName; if ($selOne) { $mapperRelatedContactDetailsVal = $selOne; if ($selTwo) { if ($selOne == 'url') { $header[] = $websiteTypes[$selTwo]; $mapperRelatedContactWebsiteTypeVal = $selTwo; } else { $header[] = $locationTypes[$selTwo]; $mapperRelatedContactLocTypeVal = $selTwo; if ($selThree) { if ($selOne == 'phone') { $header[] = $phoneTypes[$selThree]; $mapperRelatedContactPhoneTypeVal = $selThree; } elseif ($selOne == 'im') { $header[] = $imProviders[$selThree]; $mapperRelatedContactImProviderVal = $selThree; } } } } } } $mapperFields[] = implode(' - ', $header); //set the respective mapper param array values. foreach ($mapperPeroperties as $mapperProKey => $mapperProVal) { $this->{"_{$mapperProKey}"}[$key] = ${$mapperProVal}; } } $this->_parser = new CRM_Contact_Import_Parser_Contact($this->_mapperKeys, $this->_mapperLocTypes, $this->_mapperPhoneTypes, $this->_mapperImProviders, $this->_mapperRelated, $this->_mapperRelatedContactType, $this->_mapperRelatedContactDetails, $this->_mapperRelatedContactLocType, $this->_mapperRelatedContactPhoneType, $this->_mapperRelatedContactImProvider, $this->_mapperWebsiteTypes, $this->_mapperRelatedContactWebsiteType); $this->_parser->run($this->_tableName, $mapperFields, CRM_Import_Parser::MODE_IMPORT, $this->_contactType, $this->_primaryKeyName, $this->_statusFieldName, $this->_onDuplicate, $this->_statusID, $this->_totalRowCount, $this->_doGeocodeAddress, CRM_Contact_Import_Parser::DEFAULT_TIMEOUT, $this->_contactSubType, $this->_dedupe); $contactIds = $this->_parser->getImportedContacts(); //get the related contactIds. CRM-2926 $relatedContactIds = $this->_parser->getRelatedImportedContacts(); if ($relatedContactIds) { $contactIds = array_merge($contactIds, $relatedContactIds); if ($form) { $form->set('relatedCount', count($relatedContactIds)); } } if ($this->_newGroupName || count($this->_groups)) { $groupAdditions = $this->_addImportedContactsToNewGroup($contactIds, $this->_newGroupName, $this->_newGroupDesc); if ($form) { $form->set('groupAdditions', $groupAdditions); } } if ($this->_newTagName || count($this->_tag)) { $tagAdditions = $this->_tagImportedContactsWithNewTag($contactIds, $this->_newTagName, $this->_newTagDesc); if ($form) { $form->set('tagAdditions', $tagAdditions); } } }
/** * Global validation rules for the form. * * @param array $values * @param array $files * @param CRM_Core_Form $self * * @return array * list of errors to be posted back to the form */ public static function formRule($values, $files, $self) { if (!empty($values['addMore']) || !empty($values['addBlock'])) { return TRUE; } $fields = self::fields(); $fld = CRM_Core_BAO_Mapping::formattedFields($values, TRUE); $errorMsg = array(); foreach ($fld as $k => $v) { if (!$v[1]) { $errorMsg["operator[{$v['3']}][{$v['4']}]"] = ts("Please enter the operator."); } else { // CRM-10338 $v[2] = self::checkArrayKeyEmpty($v[2]); if (in_array($v[1], array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) && !empty($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts('Please clear your value if you want to use %1 operator.', array(1 => $v[1])); } elseif (substr($v[0], 0, 7) === 'do_not_' or substr($v[0], 0, 3) === 'is_') { if (isset($v[2])) { $v2 = array($v[2]); if (!isset($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a value."); } $error = CRM_Utils_Type::validate($v2[0], 'Integer', FALSE); if ($error != $v2[0]) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a valid value."); } } else { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a value."); } } else { if (substr($v[0], 0, 7) == 'custom_') { // Get rid of appended location type id list($fieldKey) = explode('-', $v[0]); $type = $fields[$fieldKey]['data_type']; // hack to handle custom data of type state and country if (in_array($type, array('Country', 'StateProvince'))) { $type = "Integer"; } } else { $fldName = $v[0]; // FIXME: no idea at this point what to do with this, // FIXME: but definitely needs fixing. if (substr($v[0], 0, 13) == 'contribution_') { $fldName = substr($v[0], 13); } $fldValue = CRM_Utils_Array::value($fldName, $fields); $fldType = CRM_Utils_Array::value('type', $fldValue); $type = CRM_Utils_Type::typeToString($fldType); if (strstr($v[1], 'IN')) { if (empty($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a value."); } } elseif (!in_array($v[1], array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) { if (($type == 'Int' || $type == 'Boolean') && !is_array($v[2]) && !trim($v[2]) && $v[2] != '0') { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a value."); } elseif ($type == 'Date' && !trim($v[2])) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a value."); } } } if ($type && empty($errorMsg)) { // check for valid format while using IN Operator if (strstr($v[1], 'IN')) { if (!is_array($v[2])) { $inVal = trim($v[2]); //checking for format to avoid db errors if ($type == 'Int') { if (!preg_match('/^[A-Za-z0-9\\,]+$/', $inVal)) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter correct Data (in valid format)."); } } else { if (!preg_match('/^[A-Za-z0-9åäöÅÄÖüÜœŒæÆøØ()\\,\\s]+$/', $inVal)) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter correct Data (in valid format)."); } } } // Validate each value in parenthesis to avoid db errors if (empty($errorMsg)) { $parenValues = array(); $parenValues = is_array($v[2]) ? array_key_exists($v[1], $v[2]) ? $v[2][$v[1]] : $v[2] : explode(',', trim($inVal, "(..)")); foreach ($parenValues as $val) { if ($type == 'Date' || $type == 'Timestamp') { $val = CRM_Utils_Date::processDate($val); if ($type == 'Date') { $val = substr($val, 0, 8); } } else { $val = trim($val); } if (!$val && $val != '0') { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the values correctly."); } if (empty($errorMsg)) { $error = CRM_Utils_Type::validate($val, $type, FALSE); if ($error != $val) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a valid value."); } } } } } elseif (trim($v[2])) { //else check value for rest of the Operators $error = CRM_Utils_Type::validate($v[2], $type, FALSE); if ($error != $v[2]) { $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter a valid value."); } } } } } } if (!empty($errorMsg)) { $self->set('showSearchForm', TRUE); $self->assign('rows', NULL); return $errorMsg; } return TRUE; }
/** * Build the mapping form. * * @param CRM_Core_Form $form * @param string $mappingType * (Export/Import/Search Builder). * @param int $mappingId * @param int $columnNo * @param int $blockCount * (no of blocks shown). * @param NULL $exportMode * * @return void */ public static function buildMappingForm(&$form, $mappingType = 'Export', $mappingId = NULL, $columnNo, $blockCount = 3, $exportMode = NULL) { $name = "Map"; $columnCount = array('1' => $columnNo); $form->applyFilter('saveMappingName', 'trim'); //to save the current mappings if (!isset($mappingId)) { $saveDetailsName = ts('Save this field mapping'); $form->add('text', 'saveMappingName', ts('Name')); $form->add('text', 'saveMappingDesc', ts('Description')); } else { $form->assign('loadedMapping', $mappingId); $params = array('id' => $mappingId); $temp = array(); $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp); $form->assign('savedName', $mappingDetails->name); $form->add('hidden', 'mappingId', $mappingId); $form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL); $saveDetailsName = ts('Save as a new field mapping'); $form->add('text', 'saveMappingName', ts('Name')); $form->add('text', 'saveMappingDesc', ts('Description')); } $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)")); $form->addFormRule(array('CRM_Export_Form_Map', 'formRule'), $form->get('mappingTypeId')); $defaults = array(); $hasLocationTypes = array(); $hasRelationTypes = array(); $fields = array(); if ($mappingType == 'Export') { $required = TRUE; } $fields = CRM_Contact_BAO_Relationship::fields(); // add custom fields $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Relationship')); ksort($fields); // add component fields $compArray = array(); foreach ($fields as $key => $value) { //CRM-2676, replacing the conflict for same custom field name from different custom group. $customGroupName = self::getCustomGroupName($key); if ($customGroupName) { $relatedMapperFields[$key] = $mapperFields[$key] = $customGroupName . ': ' . $value['title']; } else { $relatedMapperFields[$key] = $mapperFields[$key] = $value['title']; } } $mapperKeys = array_keys($mapperFields); $sel1 = array('' => ts('- select field -')) + $mapperFields; if (isset($mappingId)) { $colCnt = 0; list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue) = CRM_Core_BAO_Mapping::getMappingFields($mappingId); $blkCnt = count($mappingName); if ($blkCnt >= $blockCount) { $blockCount = $blkCnt + 1; } for ($x = 1; $x < $blockCount; $x++) { if (isset($mappingName[$x])) { $colCnt = count($mappingName[$x]); if ($colCnt >= $columnCount[$x]) { $columnCount[$x] = $colCnt; } } } } $form->_blockCount = $blockCount; $form->_columnCount = $columnCount; $form->set('blockCount', $form->_blockCount); $form->set('columnCount', $form->_columnCount); $defaults = $noneArray = $nullArray = array(); //used to warn for mismatch column count or mismatch mapping $warning = 0; for ($x = 1; $x < $blockCount; $x++) { for ($i = 0; $i < $columnCount[$x]; $i++) { $sel =& $form->addElement('hierselect', "mapper[{$x}][{$i}]", ts('Mapper for Field %1', array(1 => $i)), NULL); $jsSet = FALSE; if (isset($mappingId)) { //TODO opgeslagen mappings } //Fix for Export $j = 7; $formValues = $form->exportValues(); if (!$jsSet) { if (empty($formValues)) { // Incremented length for third select box(relationship type) for ($k = 1; $k < $j; $k++) { $noneArray[] = array($x, $i, $k); } } else { if (!empty($formValues['mapper'][$x])) { foreach ($formValues['mapper'][$x] as $value) { for ($k = 1; $k < $j; $k++) { if (!isset($formValues['mapper'][$x][$i][$k]) || !$formValues['mapper'][$x][$i][$k]) { $noneArray[] = array($x, $i, $k); } else { $nullArray[] = array($x, $i, $k); } } } } else { for ($k = 1; $k < $j; $k++) { $noneArray[] = array($x, $i, $k); } } } } //Fix for Export $sel->setOptions(array($sel1)); } $title = ts('Select more fields'); $form->addElement('submit', "addMore[{$x}]", $title, array('class' => 'submit-link')); } //end of block for $js = "<script type='text/javascript'>\n"; $formName = "document.{$name}"; if (!empty($nullArray)) { $js .= "var nullArray = ["; $elements = array(); $seen = array(); foreach ($nullArray as $element) { $key = "{$element[0]}, {$element[1]}, {$element[2]}"; if (!isset($seen[$key])) { $elements[] = "[{$key}]"; $seen[$key] = 1; } } $js .= implode(', ', $elements); $js .= "]"; $js .= "\n for (var i=0;i<nullArray.length;i++) {\n if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {\n {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';\n }\n }\n"; } if (!empty($noneArray)) { $js .= "var noneArray = ["; $elements = array(); $seen = array(); foreach ($noneArray as $element) { $key = "{$element[0]}, {$element[1]}, {$element[2]}"; if (!isset($seen[$key])) { $elements[] = "[{$key}]"; $seen[$key] = 1; } } $js .= implode(', ', $elements); $js .= "]"; $js .= "\n for (var i=0;i<noneArray.length;i++) {\n if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {\n {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';\n }\n }\n"; } $js .= "</script>\n"; $form->assign('initHideBoxes', $js); $form->assign('columnCount', $columnCount); $form->assign('blockCount', $blockCount); $form->setDefaults($defaults); $form->setDefaultAction('refresh'); }
/** * Process the form submission. * * @param array $params * @param string $db * @param \CRM_Core_Form $form */ public function postProcess(&$params, &$db, &$form) { $file = $params['uploadFile']['name']; $result = self::_CsvToTable($db, $file, CRM_Utils_Array::value('skipColumnHeader', $params, FALSE), CRM_Utils_Array::value('import_table_name', $params), CRM_Utils_Array::value('fieldSeparator', $params, ',')); $form->set('originalColHeader', CRM_Utils_Array::value('original_col_header', $result)); $table = $result['import_table_name']; $importJob = new CRM_Contact_Import_ImportJob($table); $form->set('importTableName', $importJob->getTableName()); }