Esempio n. 1
0
 /**
  * Prepare a set of search fields
  *
  * @param CRM_Core_Form $form modifiable
  * @return void
  */
 function buildForm(&$form)
 {
     CRM_Utils_System::setTitle(ts('Find Post Code'));
     $form->add('text', 'post_code', 'Post Code');
     $form->add('select', 'post_city', 'Post City', $this->citiesList);
     $defaults = $this->retrieveDefaultValues();
     if (!empty($defaults)) {
         $form->setDefaults($defaults);
     }
     $form->assign('elements', array('post_code', 'post_city'));
 }
Esempio n. 2
0
 /**
  * Prepare a set of search fields
  *
  * @param CRM_Core_Form $form modifiable
  * @return void
  */
 function buildForm(&$form)
 {
     CRM_Utils_System::setTitle(ts('My Search Title'));
     $form->add('text', 'household_name', ts('Household Name'), TRUE);
     $stateProvince = array('' => ts('- any state/province -')) + CRM_Core_PseudoConstant::stateProvince();
     $form->addElement('select', 'state_province_id', ts('State/Province'), $stateProvince);
     // Optionally define default search values
     $form->setDefaults(array('household_name' => '', 'state_province_id' => NULL));
     /**
      * if you are using the standard template, this array tells the template what elements
      * are part of the search criteria
      */
     $form->assign('elements', array('household_name', 'state_province_id'));
 }
 /**
  * @param CRM_Core_Form $form
  */
 public static function basic(&$form)
 {
     $form->addElement('hidden', 'hidden_basic', 1);
     // text for sort_name
     $form->addElement('text', 'target_name', ts('Target Contact'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
     $allRelationshipType = array();
     $allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
     $form->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $allRelationshipType, FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple'));
     // relation status
     $relStatusOption = array(ts('Active'), ts('Inactive'), ts('All'));
     $form->addRadio('is_active', ts('Relationship Status'), $relStatusOption);
     $form->setDefaults(array('is_active' => 0));
     CRM_Core_Form_Date::buildDateRange($form, 'start_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE);
     CRM_Core_Form_Date::buildDateRange($form, 'end_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE);
 }
Esempio n. 4
0
 /**
  * Prepare a set of search fields
  *
  * @param CRM_Core_Form $form modifiable
  * @return void
  */
 function buildForm(&$form)
 {
     CRM_Utils_System::setTitle(ts('Search for Players on Teams'));
     $form->add('text', 'contact_id', ts('Player ID'), TRUE);
     $form->add('text', 'group_id', ts('Team ID'), TRUE);
     //$team = array('' => ts('- any team -')) + CRM_Core_PseudoConstant::stateProvince();
     //$form->addElement('select', 'group_id', ts('Team'), $team);
     // Optionally define default search values
     $form->setDefaults(array('contact_id' => '', 'group_id' => NULL));
     /**
      * if you are using the standard template, this array tells the template what elements
      * are part of the search criteria
      */
     $form->assign('elements', array('contact_id', 'group_id'));
 }
Esempio n. 5
0
 /**
  * Build tag widget if correct parent is passed
  *
  * @param CRM_Core_Form $form
  *   Form object.
  * @param string $parentNames
  *   Parent name ( tag name).
  * @param string $entityTable
  *   Entitytable 'eg: civicrm_contact'.
  * @param int $entityId
  *   Entityid 'eg: contact id'.
  * @param bool $skipTagCreate
  *   True if tag need be created using ajax.
  * @param bool $skipEntityAction
  *   True if need to add entry in entry table via ajax.
  * @param string $tagsetElementName
  *   If you need to create tagsetlist with specific name.
  */
 public static function buildQuickForm(&$form, $parentNames, $entityTable, $entityId = NULL, $skipTagCreate = FALSE, $skipEntityAction = FALSE, $tagsetElementName = NULL)
 {
     $tagset = $form->_entityTagValues = array();
     $form->assign("isTagset", FALSE);
     $mode = NULL;
     foreach ($parentNames as &$parentNameItem) {
         // get the parent id for tag list input for keyword
         $parentId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $parentNameItem, 'id', 'name');
         // check if parent exists
         if ($parentId) {
             $tagsetItem = $tagsetElementName . 'parentId_' . $parentId;
             $tagset[$tagsetItem]['parentID'] = $parentId;
             list(, $mode) = explode('_', $entityTable);
             if (!$tagsetElementName) {
                 $tagsetElementName = $mode . "_taglist";
             }
             $tagset[$tagsetItem]['tagsetElementName'] = $tagsetElementName;
             $form->addEntityRef("{$tagsetElementName}[{$parentId}]", $parentNameItem, array('entity' => 'tag', 'multiple' => TRUE, 'create' => !$skipTagCreate, 'api' => array('params' => array('parent_id' => $parentId)), 'data-entity_table' => $entityTable, 'data-entity_id' => $entityId, 'class' => "crm-{$mode}-tagset"));
             if ($entityId) {
                 $tagset[$tagsetItem]['entityId'] = $entityId;
                 $entityTags = CRM_Core_BAO_EntityTag::getChildEntityTags($parentId, $entityId, $entityTable);
                 if ($entityTags) {
                     $form->setDefaults(array("{$tagsetElementName}[{$parentId}]" => implode(',', array_keys($entityTags))));
                 }
             } else {
                 $skipEntityAction = TRUE;
             }
             $tagset[$tagsetItem]['skipEntityAction'] = $skipEntityAction;
         }
     }
     if (!empty($tagset)) {
         // assign current tagsets which is used in postProcess
         $form->_tagsetInfo = $tagset;
         $form->assign("tagsetType", $mode);
         // Merge this tagset info with possibly existing info in the template
         $tagsetInfo = (array) $form->get_template_vars("tagsetInfo");
         if (empty($tagsetInfo[$mode])) {
             $tagsetInfo[$mode] = array();
         }
         $tagsetInfo[$mode] = array_merge($tagsetInfo[$mode], $tagset);
         $form->assign("tagsetInfo", $tagsetInfo);
         $form->assign("isTagset", TRUE);
     }
 }
Esempio n. 6
0
 /**
  * Add profile field to a form.
  *
  * @param CRM_Core_Form $form
  * @param array $field
  *   Properties.
  * @param int $mode
  *   Profile mode.
  * @param int $contactId
  * @param bool $online
  * @param string $usedFor
  *   For building up prefixed fieldname for special cases (e.g. onBehalf, Honor).
  * @param int $rowNumber
  * @param string $prefix
  *
  * @return null
  */
 public static function buildProfile(&$form, &$field, $mode, $contactId = NULL, $online = FALSE, $usedFor = NULL, $rowNumber = NULL, $prefix = '')
 {
     $defaultValues = array();
     $fieldName = $field['name'];
     $title = $field['title'];
     $attributes = $field['attributes'];
     $rule = $field['rule'];
     $view = $field['is_view'];
     $required = $mode == CRM_Profile_Form::MODE_SEARCH ? FALSE : $field['is_required'];
     $search = $mode == CRM_Profile_Form::MODE_SEARCH ? TRUE : FALSE;
     $isShared = CRM_Utils_Array::value('is_shared', $field, 0);
     // do not display view fields in drupal registration form
     // CRM-4632
     if ($view && $mode == CRM_Profile_Form::MODE_REGISTER) {
         return NULL;
     }
     if ($usedFor == 'onbehalf') {
         $name = "onbehalf[{$fieldName}]";
     } elseif ($usedFor == 'honor') {
         $name = "honor[{$fieldName}]";
     } elseif ($contactId && !$online) {
         $name = "field[{$contactId}][{$fieldName}]";
     } elseif ($rowNumber) {
         $name = "field[{$rowNumber}][{$fieldName}]";
     } elseif (!empty($prefix)) {
         $name = $prefix . "[{$fieldName}]";
     } else {
         $name = $fieldName;
     }
     $selectAttributes = array('class' => 'crm-select2', 'placeholder' => TRUE);
     if ($fieldName == 'image_URL' && $mode == CRM_Profile_Form::MODE_EDIT) {
         $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.'));
         $deleteURL = array(CRM_Core_Action::DELETE => array('name' => ts('Delete Contact Image'), 'url' => 'civicrm/contact/image', 'qs' => 'reset=1&id=%%id%%&gid=%%gid%%&action=delete', 'extra' => 'onclick = "' . htmlspecialchars("if (confirm({$deleteExtra})) this.href+='&confirmed=1'; else return false;") . '"'));
         $deleteURL = CRM_Core_Action::formLink($deleteURL, CRM_Core_Action::DELETE, array('id' => $form->get('id'), 'gid' => $form->get('gid')), ts('more'), FALSE, 'contact.profileimage.delete', 'Contact', $form->get('id'));
         $form->assign('deleteURL', $deleteURL);
     }
     $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options', TRUE, NULL, TRUE);
     if (substr($fieldName, 0, 14) === 'state_province') {
         $form->addChainSelect($name, array('label' => $title, 'required' => $required));
         $config = CRM_Core_Config::singleton();
         if (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)) && $config->defaultContactStateProvince) {
             $defaultValues[$name] = $config->defaultContactStateProvince;
             $form->setDefaults($defaultValues);
         }
     } elseif (substr($fieldName, 0, 7) === 'country') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::country(), $required, $selectAttributes);
         $config = CRM_Core_Config::singleton();
         if (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)) && $config->defaultContactCountry) {
             $defaultValues[$name] = $config->defaultContactCountry;
             $form->setDefaults($defaultValues);
         }
     } elseif (substr($fieldName, 0, 6) === 'county') {
         if ($addressOptions['county']) {
             $form->addChainSelect($name, array('label' => $title, 'required' => $required));
         }
     } elseif (substr($fieldName, 0, 9) === 'image_URL') {
         $form->add('file', $name, $title, $attributes, $required);
         $form->addUploadElement($name);
     } elseif (substr($fieldName, 0, 2) === 'im') {
         $form->add('text', $name, $title, $attributes, $required);
         if (!$contactId) {
             if ($usedFor) {
                 if (substr($name, -1) == ']') {
                     $providerName = substr($name, 0, -1) . '-provider_id]';
                 }
                 $form->add('select', $providerName, NULL, array('' => ts('- select -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'), $required);
             } else {
                 $form->add('select', $name . '-provider_id', $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'), $required);
             }
             if ($view && $mode != CRM_Profile_Form::MODE_SEARCH) {
                 $form->freeze($name . '-provider_id');
             }
         }
     } elseif ($fieldName === 'birth_date' || $fieldName === 'deceased_date') {
         $form->addDate($name, $title, $required, array('formatType' => 'birth'));
     } elseif (in_array($fieldName, array('membership_start_date', 'membership_end_date', 'join_date'))) {
         $form->addDate($name, $title, $required, array('formatType' => 'activityDate'));
     } elseif (CRM_Utils_Array::value('name', $field) == 'membership_type') {
         list($orgInfo, $types) = CRM_Member_BAO_MembershipType::getMembershipTypeInfo();
         $sel =& $form->addElement('hierselect', $name, $title);
         $select = array('' => ts('- select -'));
         if (count($orgInfo) == 1 && $field['is_required']) {
             // we only have one org - so we should default to it. Not sure about defaulting to first type
             // as it could be missed - so adding a select
             // however, possibly that is more similar to the membership form
             if (count($types[1]) > 1) {
                 $types[1] = $select + $types[1];
             }
         } else {
             $orgInfo = $select + $orgInfo;
         }
         $sel->setOptions(array($orgInfo, $types));
     } elseif (CRM_Utils_Array::value('name', $field) == 'membership_status') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'), $required);
     } elseif (in_array($fieldName, array('gender_id', 'communication_style_id'))) {
         $options = array();
         $pseudoValues = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', $fieldName);
         foreach ($pseudoValues as $key => $var) {
             $options[$key] = $form->createElement('radio', NULL, ts($title), $var, $key);
         }
         $group = $form->addGroup($options, $name, $title);
         if ($required) {
             $form->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required');
         } else {
             $group->setAttribute('allowClear', TRUE);
         }
     } elseif ($fieldName === 'prefix_id' || $fieldName === 'suffix_id') {
         $form->addSelect($name, array('label' => $title, 'entity' => 'contact', 'field' => $fieldName, 'class' => 'six', 'placeholder' => ''), $required);
     } elseif ($fieldName === 'contact_sub_type') {
         $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $field);
         if ($usedFor == 'onbehalf') {
             $profileType = 'Organization';
         } elseif ($usedFor == 'honor') {
             $profileType = CRM_Core_BAO_UFField::getProfileType($form->_params['honoree_profile_id']);
         } else {
             $profileType = $gId ? CRM_Core_BAO_UFField::getProfileType($gId) : NULL;
             if ($profileType == 'Contact') {
                 $profileType = 'Individual';
             }
         }
         $setSubtype = FALSE;
         if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
             $setSubtype = $profileType;
             $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
         }
         $subtypes = $profileType ? CRM_Contact_BAO_ContactType::subTypePairs($profileType) : array();
         if ($setSubtype) {
             $subtypeList = array();
             $subtypeList[$setSubtype] = $subtypes[$setSubtype];
         } else {
             $subtypeList = $subtypes;
         }
         $form->add('select', $name, $title, $subtypeList, $required, array('class' => 'crm-select2', 'multiple' => TRUE));
     } elseif (in_array($fieldName, CRM_Contact_BAO_Contact::$_greetingTypes)) {
         //add email greeting, postal greeting, addressee, CRM-4575
         $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $field);
         $profileType = CRM_Core_BAO_UFField::getProfileType($gId, TRUE, FALSE, TRUE);
         if (empty($profileType) || in_array($profileType, array('Contact', 'Contribution', 'Participant', 'Membership'))) {
             $profileType = 'Individual';
         }
         if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
             $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
         }
         $greeting = array('contact_type' => $profileType, 'greeting_type' => $fieldName);
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($greeting), $required);
         // add custom greeting element
         $form->add('text', $fieldName . '_custom', ts('Custom %1', array(1 => ucwords(str_replace('_', ' ', $fieldName)))), NULL, FALSE);
     } elseif ($fieldName === 'preferred_communication_method') {
         $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
         foreach ($communicationFields as $key => $var) {
             if ($key == '') {
                 continue;
             }
             $communicationOptions[] = $form->createElement('checkbox', $key, NULL, $var);
         }
         $form->addGroup($communicationOptions, $name, $title, '<br/>');
     } elseif ($fieldName === 'preferred_mail_format') {
         $form->add('select', $name, $title, CRM_Core_SelectValues::pmf());
     } elseif ($fieldName === 'preferred_language') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contact_BAO_Contact::buildOptions('preferred_language'));
     } elseif ($fieldName == 'external_identifier') {
         $form->add('text', $name, $title, $attributes, $required);
         $contID = $contactId;
         if (!$contID) {
             $contID = $form->get('id');
         }
         $form->addRule($name, ts('External ID already exists in Database.'), 'objectExists', array('CRM_Contact_DAO_Contact', $contID, 'external_identifier'));
     } elseif ($fieldName === 'group') {
         CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::GROUP, TRUE, $required, $title, NULL, $name);
     } elseif ($fieldName === 'tag') {
         CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::TAG, FALSE, $required, NULL, $title, $name);
     } elseif (substr($fieldName, 0, 4) === 'url-') {
         $form->add('text', $name, $title, CRM_Core_DAO::getAttribute('CRM_Core_DAO_Website', 'url'), $required);
         $form->addRule($name, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'url');
     } elseif (substr($fieldName, -4) == 'note') {
         $form->add('textarea', $name, $title, $attributes, $required);
     } elseif (substr($fieldName, 0, 6) === 'custom') {
         $customFieldID = CRM_Core_BAO_CustomField::getKeyID($fieldName);
         if ($customFieldID) {
             CRM_Core_BAO_CustomField::addQuickFormElement($form, $name, $customFieldID, FALSE, $required, $search, $title);
         }
     } elseif (substr($fieldName, 0, 14) === 'address_custom') {
         list($fName, $locTypeId) = CRM_Utils_System::explode('-', $fieldName, 2);
         $customFieldID = CRM_Core_BAO_CustomField::getKeyID(substr($fName, 8));
         if ($customFieldID) {
             CRM_Core_BAO_CustomField::addQuickFormElement($form, $name, $customFieldID, FALSE, $required, $search, $title);
         }
     } elseif (in_array($fieldName, array('receive_date', 'receipt_date', 'thankyou_date', 'cancel_date'))) {
         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
     } elseif ($fieldName == 'send_receipt') {
         $form->addElement('checkbox', $name, $title);
     } elseif ($fieldName == 'soft_credit') {
         $form->addEntityRef("soft_credit_contact_id[{$rowNumber}]", ts('Soft Credit To'), array('create' => TRUE));
         $form->addMoney("soft_credit_amount[{$rowNumber}]", ts('Amount'), FALSE, NULL, FALSE);
     } elseif ($fieldName == 'product_name') {
         list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
         $sel =& $form->addElement('hierselect', $name, $title);
         $products = array('0' => ts('- select -')) + $products;
         $sel->setOptions(array($products, $options));
     } elseif ($fieldName == 'payment_instrument') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), $required);
     } elseif ($fieldName == 'financial_type') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(), $required);
     } elseif ($fieldName == 'contribution_status_id') {
         $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus();
         $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         foreach (array('In Progress', 'Overdue', 'Refunded') as $suppress) {
             unset($contributionStatuses[CRM_Utils_Array::key($suppress, $statusName)]);
         }
         $form->add('select', $name, $title, array('' => ts('- select -')) + $contributionStatuses, $required);
     } elseif ($fieldName == 'soft_credit_type') {
         $name = "soft_credit_type[{$rowNumber}]";
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_OptionGroup::values("soft_credit_type"));
         //CRM-15350: choose SCT field default value as 'Gift' for membership use
         //else (for contribution), use configured SCT default value
         $SCTDefaultValue = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type");
         if ($field['field_type'] == 'Membership') {
             $SCTDefaultValue = CRM_Core_OptionGroup::getValue('soft_credit_type', 'Gift', 'name');
         }
         $form->addElement('hidden', 'sct_default_id', $SCTDefaultValue, array('id' => 'sct_default_id'));
     } elseif ($fieldName == 'currency') {
         $form->addCurrency($name, $title, $required);
     } elseif ($fieldName == 'contribution_page_id') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionPage(), $required, 'class="big"');
     } elseif ($fieldName == 'participant_register_date') {
         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
     } elseif ($fieldName == 'activity_status_id') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::activityStatus(), $required);
     } elseif ($fieldName == 'activity_engagement_level') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Campaign_PseudoConstant::engagementLevel(), $required);
     } elseif ($fieldName == 'activity_date_time') {
         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
     } elseif ($fieldName == 'participant_status') {
         $cond = NULL;
         if ($online == TRUE) {
             $cond = 'visibility_id = 1';
         }
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantStatus(NULL, $cond, 'label'), $required);
     } elseif ($fieldName == 'participant_role') {
         if (!empty($field['is_multiple'])) {
             $form->addCheckBox($name, $title, CRM_Event_PseudoConstant::participantRole(), NULL, NULL, NULL, NULL, '&nbsp', TRUE);
         } else {
             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantRole(), $required);
         }
     } elseif ($fieldName == 'world_region') {
         $form->add('select', $name, $title, CRM_Core_PseudoConstant::worldRegion(), $required, $selectAttributes);
     } elseif ($fieldName == 'signature_html') {
         $form->add('wysiwyg', $name, $title, CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', $fieldName));
     } elseif ($fieldName == 'signature_text') {
         $form->add('textarea', $name, $title, CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', $fieldName));
     } elseif (substr($fieldName, -11) == 'campaign_id') {
         if (CRM_Campaign_BAO_Campaign::isCampaignEnable()) {
             $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns(CRM_Utils_Array::value($contactId, $form->_componentCampaigns));
             $form->add('select', $name, $title, array('' => ts('- select -')) + $campaigns, $required, 'class="crm-select2 big"');
         }
     } elseif ($fieldName == 'activity_details') {
         $form->add('wysiwyg', $fieldName, $title, array('rows' => 4, 'cols' => 60), $required);
     } elseif ($fieldName == 'activity_duration') {
         $form->add('text', $name, $title, $attributes, $required);
         $form->addRule($name, ts('Please enter the duration as number of minutes (integers only).'), 'positiveInteger');
     } else {
         if (substr($fieldName, 0, 3) === 'is_' or substr($fieldName, 0, 7) === 'do_not_') {
             $form->add('advcheckbox', $name, $title, $attributes, $required);
         } else {
             $form->add('text', $name, $title, $attributes, $required);
         }
     }
     static $hiddenSubtype = FALSE;
     if (!$hiddenSubtype && CRM_Contact_BAO_ContactType::isaSubType($field['field_type'])) {
         // In registration mode params are submitted via POST and we don't have any clue
         // about profile-id or the profile-type (which could be a subtype)
         // To generalize the  behavior and simplify the process,
         // lets always add the hidden
         //subtype value if there is any, and we won't have to
         // compute it while processing.
         if ($usedFor) {
             $form->addElement('hidden', $usedFor . '[contact_sub_type]', $field['field_type']);
         } else {
             $form->addElement('hidden', 'contact_sub_type_hidden', $field['field_type']);
         }
         $hiddenSubtype = TRUE;
     }
     if ($view && $mode != CRM_Profile_Form::MODE_SEARCH || $isShared) {
         $form->freeze($name);
     }
     //add the rules
     if (in_array($fieldName, array('non_deductible_amount', 'total_amount', 'fee_amount', 'net_amount'))) {
         $form->addRule($name, ts('Please enter a valid amount.'), 'money');
     }
     if ($rule) {
         if (!($rule == 'email' && $mode == CRM_Profile_Form::MODE_SEARCH)) {
             $form->addRule($name, ts('Please enter a valid %1', array(1 => $title)), $rule);
         }
     }
 }
Esempio n. 7
0
 /**
  * This function for building custom fields.
  *
  * @param CRM_Core_Form $qf
  *   Form object (reference).
  * @param string $elementName
  *   Name of the custom field.
  * @param int $fieldId
  * @param bool $inactiveNeeded
  *   -deprecated.
  * @param bool $useRequired
  *   True if required else false.
  * @param bool $search
  *   True if used for search else false.
  * @param string $label
  *   Label for custom field.
  *
  */
 public static function addQuickFormElement(&$qf, $elementName, $fieldId, $inactiveNeeded = FALSE, $useRequired = TRUE, $search = FALSE, $label = NULL)
 {
     $field = self::getFieldObject($fieldId);
     $widget = $field->html_type;
     // Custom field HTML should indicate group+field name
     $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id);
     $dataCrmCustomVal = $groupName . ':' . $field->name;
     $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
     $field->attributes .= $dataCrmCustomAttr;
     // Fixed for Issue CRM-2183
     if ($widget == 'TextArea' && $search) {
         $widget = 'Text';
     }
     $placeholder = $search ? ts('- any -') : ($useRequired ? ts('- select -') : ts('- none -'));
     // FIXME: Why are select state/country separate widget types?
     $isSelect = in_array($widget, array('Select', 'Multi-Select', 'Select State/Province', 'Multi-Select State/Province', 'Select Country', 'Multi-Select Country', 'AdvMulti-Select', 'CheckBox', 'Radio'));
     if ($isSelect) {
         $options = CRM_Utils_Array::value('values', civicrm_api3('contact', 'getoptions', array('field' => "custom_{$fieldId}", 'context' => $search ? 'search' : 'create'), array()));
         // Consolidate widget types to simplify the below switch statement
         if ($search || $widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE) {
             $widget = 'Select';
         }
         $selectAttributes = array('data-crm-custom' => $dataCrmCustomVal, 'class' => 'crm-select2');
         // Search field is always multi-select
         if ($search || strpos($field->html_type, 'Multi') !== FALSE) {
             $selectAttributes['class'] .= ' huge';
             $selectAttributes['multiple'] = 'multiple';
             $selectAttributes['placeholder'] = $placeholder;
         }
         // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
         if ($field->option_group_id && !$search && $widget == 'Select' && CRM_Core_Permission::check('administer CiviCRM')) {
             $selectAttributes += array('data-api-entity' => 'contact', 'data-api-field' => 'custom_' . $field->id, 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id));
         }
     }
     if (!isset($label)) {
         $label = $field->label;
     }
     /**
      * at some point in time we might want to split the below into small functions
      **/
     switch ($widget) {
         case 'Text':
         case 'Link':
             if ($field->is_search_range && $search) {
                 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
                 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
             } else {
                 $element =& $qf->add('text', $elementName, $label, $field->attributes, $useRequired && !$search);
             }
             break;
         case 'TextArea':
             $attributes = $dataCrmCustomAttr;
             if ($field->note_rows) {
                 $attributes .= 'rows=' . $field->note_rows;
             } else {
                 $attributes .= 'rows=4';
             }
             if ($field->note_columns) {
                 $attributes .= ' cols=' . $field->note_columns;
             } else {
                 $attributes .= ' cols=60';
             }
             if ($field->text_length) {
                 $attributes .= ' maxlength=' . $field->text_length;
             }
             $element =& $qf->add('textarea', $elementName, $label, $attributes, $useRequired && !$search);
             break;
         case 'Select Date':
             if ($field->is_search_range && $search) {
                 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE, array('format' => $field->date_format, 'timeFormat' => $field->time_format, 'startOffset' => $field->start_date_years, 'endOffset' => $field->end_date_years, 'data-crm-custom' => $dataCrmCustomVal));
                 $qf->addDate($elementName . '_to', ts('To'), FALSE, array('format' => $field->date_format, 'timeFormat' => $field->time_format, 'startOffset' => $field->start_date_years, 'endOffset' => $field->end_date_years, 'data-crm-custom' => $dataCrmCustomVal));
             } else {
                 $required = $useRequired && !$search;
                 $qf->addDate($elementName, $label, $required, array('format' => $field->date_format, 'timeFormat' => $field->time_format, 'startOffset' => $field->start_date_years, 'endOffset' => $field->end_date_years, 'data-crm-custom' => $dataCrmCustomVal));
             }
             break;
         case 'Radio':
             $choice = array();
             foreach ($options as $v => $l) {
                 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes);
             }
             $group = $qf->addGroup($choice, $elementName, $label);
             if ($useRequired && !$search) {
                 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
             } else {
                 $group->setAttribute('allowClear', TRUE);
             }
             break;
             // For all select elements
         // For all select elements
         case 'Select':
             if (empty($selectAttributes['multiple'])) {
                 $options = array('' => $placeholder) + $options;
             }
             $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
             // Add and/or option for fields that store multiple values
             if ($search && self::isSerialized($field)) {
                 $operators = array($qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))), $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))));
                 $qf->addGroup($operators, $elementName . '_operator');
                 $qf->setDefaults(array($elementName . '_operator' => 'or'));
             }
             break;
         case 'AdvMulti-Select':
             $include =& $qf->addElement('advmultiselect', $elementName, $label, $options, array('size' => 5, 'style' => '', 'class' => 'advmultiselect', 'data-crm-custom' => $dataCrmCustomVal));
             $include->setButtonAttributes('add', array('value' => ts('Add >>')));
             $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
             if ($useRequired && !$search) {
                 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
             }
             break;
         case 'CheckBox':
             $check = array();
             foreach ($options as $v => $l) {
                 $check[] =& $qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
             }
             $qf->addGroup($check, $elementName, $label);
             if ($useRequired && !$search) {
                 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
             }
             break;
         case 'File':
             // we should not build upload file in search mode
             if ($search) {
                 return;
             }
             $qf->add(strtolower($field->html_type), $elementName, $label, $field->attributes, $useRequired && !$search);
             $qf->addUploadElement($elementName);
             break;
         case 'RichTextEditor':
             $attributes = array('rows' => $field->note_rows, 'cols' => $field->note_columns, 'data-crm-custom' => $dataCrmCustomVal);
             if ($field->text_length) {
                 $attributes['maxlength'] = $field->text_length;
             }
             $qf->addWysiwyg($elementName, $label, $attributes, $search);
             break;
         case 'Autocomplete-Select':
             static $customUrls = array();
             // Fixme: why is this a string in the first place??
             $attributes = array();
             if ($field->attributes) {
                 foreach (explode(' ', $field->attributes) as $at) {
                     if (strpos($at, '=')) {
                         list($k, $v) = explode('=', $at);
                         $attributes[$k] = trim($v, ' "');
                     }
                 }
             }
             if ($field->data_type == 'ContactReference') {
                 $attributes['class'] = (isset($attributes['class']) ? $attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
                 $attributes['data-api-entity'] = 'contact';
                 $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
                 $urlParams = "context=customfield&id={$field->id}";
                 $customUrls[$elementName] = CRM_Utils_System::url('civicrm/ajax/contactref', $urlParams, FALSE, NULL, FALSE);
             } else {
                 // FIXME: This won't work with customFieldOptions hook
                 $attributes += array('entity' => 'option_value', 'placeholder' => $placeholder, 'multiple' => $search, 'api' => array('params' => array('option_group_id' => $field->option_group_id)));
                 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
             }
             $qf->assign('customUrls', $customUrls);
             break;
     }
     switch ($field->data_type) {
         case 'Int':
             // integers will have numeric rule applied to them.
             if ($field->is_search_range && $search) {
                 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
                 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
             } elseif ($widget == 'Text') {
                 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
             }
             break;
         case 'Float':
             if ($field->is_search_range && $search) {
                 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
                 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
             } elseif ($widget == 'Text') {
                 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
             }
             break;
         case 'Money':
             if ($field->is_search_range && $search) {
                 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
                 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
             } elseif ($widget == 'Text') {
                 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
             }
             break;
         case 'Link':
             $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
             $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
             $element->setAttribute('class', "url");
             $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
             break;
     }
     if ($field->is_view && !$search) {
         $qf->freeze($elementName);
     }
 }
Esempio n. 8
0
 /**
  * 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');
 }
Esempio n. 9
0
 /**
  * Build Pledge Block in Contribution Pages.
  *
  * @param CRM_Core_Form $form
  */
 public static function buildPledgeBlock($form)
 {
     //build pledge payment fields.
     if (!empty($form->_values['pledge_id'])) {
         //get all payments required details.
         $allPayments = array();
         $returnProperties = array('status_id', 'scheduled_date', 'scheduled_amount', 'currency', 'pledge_start_date');
         CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $form->_values['pledge_id'], $allPayments, $returnProperties);
         // get all status
         $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         $nextPayment = array();
         $isNextPayment = FALSE;
         $overduePayments = array();
         foreach ($allPayments as $payID => $value) {
             if ($allStatus[$value['status_id']] == 'Overdue') {
                 $overduePayments[$payID] = array('id' => $payID, 'scheduled_amount' => CRM_Utils_Rule::cleanMoney($value['scheduled_amount']), 'scheduled_amount_currency' => $value['currency'], 'scheduled_date' => CRM_Utils_Date::customFormat($value['scheduled_date'], '%B %d'));
             } elseif (!$isNextPayment && $allStatus[$value['status_id']] == 'Pending') {
                 // get the next payment.
                 $nextPayment = array('id' => $payID, 'scheduled_amount' => CRM_Utils_Rule::cleanMoney($value['scheduled_amount']), 'scheduled_amount_currency' => $value['currency'], 'scheduled_date' => CRM_Utils_Date::customFormat($value['scheduled_date'], '%B %d'));
                 $isNextPayment = TRUE;
             }
         }
         // build check box array for payments.
         $payments = array();
         if (!empty($overduePayments)) {
             foreach ($overduePayments as $id => $payment) {
                 $label = ts("%1 - due on %2 (overdue)", array(1 => CRM_Utils_Money::format(CRM_Utils_Array::value('scheduled_amount', $payment), CRM_Utils_Array::value('scheduled_amount_currency', $payment)), 2 => CRM_Utils_Array::value('scheduled_date', $payment)));
                 $paymentID = CRM_Utils_Array::value('id', $payment);
                 $payments[] = $form->createElement('checkbox', $paymentID, NULL, $label, array('amount' => CRM_Utils_Array::value('scheduled_amount', $payment)));
             }
         }
         if (!empty($nextPayment)) {
             $label = ts("%1 - due on %2", array(1 => CRM_Utils_Money::format(CRM_Utils_Array::value('scheduled_amount', $nextPayment), CRM_Utils_Array::value('scheduled_amount_currency', $nextPayment)), 2 => CRM_Utils_Array::value('scheduled_date', $nextPayment)));
             $paymentID = CRM_Utils_Array::value('id', $nextPayment);
             $payments[] = $form->createElement('checkbox', $paymentID, NULL, $label, array('amount' => CRM_Utils_Array::value('scheduled_amount', $nextPayment)));
         }
         // give error if empty or build form for payment.
         if (empty($payments)) {
             CRM_Core_Error::fatal(ts("Oops. It looks like there is no valid payment status for online payment."));
         } else {
             $form->assign('is_pledge_payment', TRUE);
             $form->addGroup($payments, 'pledge_amount', ts('Make Pledge Payment(s):'), '<br />');
         }
     } else {
         $pledgeBlock = self::getPledgeBlock($form->_id);
         // build form for pledge creation.
         $pledgeOptions = array('0' => ts('I want to make a one-time contribution'), '1' => ts('I pledge to contribute this amount every'));
         $form->addRadio('is_pledge', ts('Pledge Frequency Interval'), $pledgeOptions, NULL, array('<br/>'));
         $form->addElement('text', 'pledge_installments', ts('Installments'), array('size' => 3));
         if (!empty($pledgeBlock['is_pledge_interval'])) {
             $form->assign('is_pledge_interval', CRM_Utils_Array::value('is_pledge_interval', $pledgeBlock));
             $form->addElement('text', 'pledge_frequency_interval', NULL, array('size' => 3));
         } else {
             $form->add('hidden', 'pledge_frequency_interval', 1);
         }
         // Frequency unit drop-down label suffixes switch from *ly to *(s)
         $freqUnitVals = explode(CRM_Core_DAO::VALUE_SEPARATOR, $pledgeBlock['pledge_frequency_unit']);
         $freqUnits = array();
         $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units');
         foreach ($freqUnitVals as $key => $val) {
             if (array_key_exists($val, $frequencyUnits)) {
                 $freqUnits[$val] = !empty($pledgeBlock['is_pledge_interval']) ? "{$frequencyUnits[$val]}(s)" : $frequencyUnits[$val];
             }
         }
         $form->addElement('select', 'pledge_frequency_unit', NULL, $freqUnits);
         // CRM-18854
         if (CRM_Utils_Array::value('is_pledge_start_date_visible', $pledgeBlock)) {
             if (CRM_Utils_Array::value('pledge_start_date', $pledgeBlock)) {
                 $defaults = array();
                 $date = (array) json_decode($pledgeBlock['pledge_start_date']);
                 list($field, $value) = each($date);
                 switch ($field) {
                     case 'contribution_date':
                         $form->addDate('start_date', ts('First installment payment'));
                         $paymentDate = $value = date('d/m/Y');
                         list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($value);
                         $form->assign('is_date', TRUE);
                         break;
                     case 'calendar_date':
                         $form->addDate('start_date', ts('First installment payment'));
                         list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($value);
                         $form->assign('is_date', TRUE);
                         $paymentDate = $value;
                         break;
                     case 'calendar_month':
                         $month = CRM_Utils_Date::getCalendarDayOfMonth();
                         $form->add('select', 'start_date', ts('Day of month installments paid'), $month);
                         $paymentDate = CRM_Pledge_BAO_Pledge::getPaymentDate($value);
                         list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($paymentDate);
                         break;
                     default:
                         break;
                 }
                 $form->setDefaults($defaults);
                 $form->assign('start_date_display', $paymentDate);
                 $form->assign('start_date_editable', FALSE);
                 if (CRM_Utils_Array::value('is_pledge_start_date_editable', $pledgeBlock)) {
                     $form->assign('start_date_editable', TRUE);
                     if ($field == 'calendar_month') {
                         $form->assign('is_date', FALSE);
                         $form->setDefaults(array('start_date' => $value));
                     }
                 }
             }
         }
     }
 }
Esempio n. 10
0
 /**
  * @param CRM_Core_Form $form
  */
 public function buildForm(&$form)
 {
     $config = CRM_Core_Config::singleton();
     $form->applyFilter('__ALL__', 'trim');
     $form->add('text', 'text', ts('Find'), TRUE);
     // also add a select box to allow the search to be constrained
     $tables = array('' => ts('All tables'));
     foreach ($this->_partialQueries as $partialQuery) {
         /** @var $partialQuery CRM_Contact_Form_Search_Custom_FullText_AbstractPartialQuery */
         if ($partialQuery->isActive()) {
             $tables[$partialQuery->getName()] = $partialQuery->getLabel();
         }
     }
     $form->add('select', 'table', ts('Tables'), $tables);
     $form->assign('csID', $form->get('csid'));
     // also add the limit constant
     $form->assign('limit', self::LIMIT);
     // set form defaults
     if (!empty($form->_formValues)) {
         $defaults = array();
         if (isset($form->_formValues['text'])) {
             $defaults['text'] = $form->_formValues['text'];
         }
         if (isset($form->_formValues['table'])) {
             $defaults['table'] = $form->_formValues['table'];
             $form->assign('table', $form->_formValues['table']);
         }
         $form->setDefaults($defaults);
     }
     /**
      * You can define a custom title for the search form
      */
     $this->setTitle(ts('Full-text Search'));
     $searchService = CRM_Core_BAO_File::getSearchService();
     $form->assign('allowFileSearch', !empty($searchService) && CRM_Core_Permission::check('access uploaded files'));
 }
Esempio n. 11
0
/**
 * @param string $formName
 * @param CRM_Core_Form $form
 */
function hremerg_civicrm_buildForm($formName, &$form)
{
    if ($formName == 'CRM_Contact_Form_Relationship' && empty($form->_caseId)) {
        if ($form->elementExists('relationship_type_id') && $form->_contactType == 'Individual') {
            $relationshipType = civicrm_api3('relationship_type', 'get', array('name_a_b' => 'Emergency Contact'));
            $select = $form->getElement('relationship_type_id');
            $select->freeze();
            $select->setLabel('');
            $form->getElement('related_contact_id')->setLabel('');
            if ($form->getAction() & CRM_Core_Action::ADD && !empty($relationshipType['id'])) {
                $form->setDefaults(array('relationship_type_id' => $relationshipType['id'] . '_a_b'));
            }
        }
    }
}
/**
 * Implements hook_civicrm_buildForm().
 *
 * @param string $formName
 * @param CRM_Core_Form $form
 */
function pledgeonlypage_civicrm_buildForm($formName, &$form)
{
    if ($formName == 'CRM_Contribute_Form_Contribution_Main') {
        if ($form->get('id') == 2) {
            $defaults['is_pledge'] = 1;
            $defaults['pledge_installments'] = 1;
            $defaults['pledge_frequency_interval'] = 1;
            $form->setDefaults($defaults);
            $form->addDate('pledge_start_date', ts('First payment date'), FALSE, array('formatType' => 'activityDate'));
            CRM_Core_Region::instance('contribution-main-pledge-block')->update('default', array('disabled' => TRUE));
            CRM_Core_Region::instance('contribution-main-pledge-block')->add(array('template' => 'pledgeOnlyBlock.tpl'));
        }
    }
}
Esempio n. 13
0
 /**
  * Build form for related contacts / on behalf of organization.
  *
  * @param CRM_Core_Form $form
  *
  */
 public static function buildQuickForm(&$form)
 {
     $form->assign('fieldSetTitle', ts('Organization Details'));
     $form->assign('buildOnBehalfForm', TRUE);
     $contactID = $form->_contactID;
     if ($contactID && count($form->_employers) >= 1) {
         $form->add('text', 'organization_id', ts('Select an existing related Organization OR enter a new one'));
         $form->add('select', 'onbehalfof_id', '', CRM_Utils_Array::collect('name', $form->_employers));
         $orgOptions = array(0 => ts('Select an existing organization'), 1 => ts('Enter a new organization'));
         $form->addRadio('org_option', ts('options'), $orgOptions);
         $form->setDefaults(array('org_option' => 0));
         $form->add('checkbox', 'mode', '');
     }
     $profileFields = CRM_Core_BAO_UFGroup::getFields($form->_profileId, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL);
     $fieldTypes = array('Contact', 'Organization');
     $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
     $fieldTypes = array_merge($fieldTypes, $contactSubType);
     if (is_array($form->_membershipBlock) && !empty($form->_membershipBlock)) {
         $fieldTypes = array_merge($fieldTypes, array('Membership'));
     } else {
         $fieldTypes = array_merge($fieldTypes, array('Contribution'));
     }
     foreach ($profileFields as $name => $field) {
         if (in_array($field['field_type'], $fieldTypes)) {
             list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2);
             if (in_array($prefixName, array('organization_name', 'email')) && empty($field['is_required'])) {
                 $field['is_required'] = 1;
             }
             CRM_Core_BAO_UFGroup::buildProfile($form, $field, NULL, NULL, FALSE, 'onbehalf');
         }
     }
     $form->assign('onBehalfOfFields', $profileFields);
     $form->addElement('hidden', 'hidden_onbehalf_profile', 1);
 }
 /**
  * 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');
 }
Esempio n. 15
0
 /**
  * Set the default form values.
  *
  *
  * @param CRM_Core_Form $form
  *
  * @return array
  *   the default array reference
  */
 public function setDefaultValues($form)
 {
     $defaults = array();
     $config = CRM_Core_Config::singleton();
     $countryDefault = $config->defaultContactCountry;
     if ($countryDefault) {
         $defaults['prox_country_id'] = $countryDefault;
         if ($countryDefault == '1228') {
             $defaults['prox_distance_unit'] = 'miles';
         } else {
             $defaults['prox_distance_unit'] = 'km';
         }
     }
     $form->setDefaults($defaults);
     return $defaults;
 }