3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * This class is used to build address block
39 class CRM_Contact_Form_Edit_Address
{
42 * build form for address input fields
44 * @param object $form - CRM_Core_Form (or subclass)
45 * @param int $addressBlockCount - the index of the address array (if multiple addresses on a page)
46 * @param boolean $sharing - false, if we want to skip the address sharing features
47 * @param boolean $inlineEdit true when edit used in inline edit
54 static function buildQuickForm(&$form, $addressBlockCount = NULL, $sharing = TRUE, $inlineEdit = FALSE) {
55 // passing this via the session is AWFUL. we need to fix this
56 if (!$addressBlockCount) {
57 $blockId = ($form->get('Address_Block_Count')) ?
$form->get('Address_Block_Count') : 1;
60 $blockId = $addressBlockCount;
63 $config = CRM_Core_Config
::singleton();
64 $countryDefault = $config->defaultContactCountry
;
66 $form->applyFilter('__ALL__', 'trim');
70 $js = array('onChange' => 'checkLocation( this.id );');
73 $form->addSelect("address[$blockId][location_type_id]", array('entity' => 'address', 'class' => 'eight') +
$js);
76 $js = array('id' => 'Address_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );');
79 //make location type required for inline edit
80 $form->addRule( "address[$blockId][location_type_id]", ts('%1 is a required field.', array(1 => ts('Location Type'))), 'required');
85 "address[$blockId][is_primary]",
86 ts('Primary location for this contact'),
87 ts('Primary location for this contact'),
92 $js = array('id' => 'Address_' . $blockId . '_IsBilling', 'onClick' => 'singleSelect( this.id );');
97 "address[$blockId][is_billing]",
98 ts('Billing location for this contact'),
99 ts('Billing location for this contact'),
103 // hidden element to store master address id
104 $form->addElement('hidden', "address[$blockId][master_id]");
106 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
107 'address_options', TRUE, NULL, TRUE
109 $attributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_Address');
112 'address_name' => array(ts('Address Name'), $attributes['address_name'], NULL),
113 'street_address' => array(ts('Street Address'), $attributes['street_address'], NULL),
114 'supplemental_address_1' => array(ts('Supplemental Address 1'), $attributes['supplemental_address_1'], NULL),
115 'supplemental_address_2' => array(ts('Supplemental Address 2'), $attributes['supplemental_address_2'], NULL),
116 'city' => array(ts('City'), $attributes['city'], NULL),
117 'postal_code' => array(ts('Zip / Postal Code'), array_merge($attributes['postal_code'], array('class' => 'crm_postal_code')), NULL),
118 'postal_code_suffix' => array(ts('Postal Code Suffix'), array('size' => 4, 'maxlength' => 12, 'class' => 'crm_postal_code_suffix'), NULL),
119 'county_id' => array(ts('County'), $attributes['county_id'], NULL),
120 'state_province_id' => array(ts('State / Province'), $attributes['state_province_id'], NULL),
121 'country_id' => array(ts('Country'), $attributes['country_id'], NULL),
122 'geo_code_1' => array(ts('Latitude'), array('size' => 9, 'maxlength' => 11), NULL),
123 'geo_code_2' => array(ts('Longitude'), array('size' => 9, 'maxlength' => 11), NULL),
124 'street_number' => array(ts('Street Number'), $attributes['street_number'], NULL),
125 'street_name' => array(ts('Street Name'), $attributes['street_name'], NULL),
126 'street_unit' => array(ts('Apt/Unit/Suite'), $attributes['street_unit'], NULL),
129 $stateCountryMap = array();
130 foreach ($elements as $name => $v) {
131 list($title, $attributes, $select) = $v;
133 $nameWithoutID = strpos($name, '_id') !== FALSE ?
substr($name, 0, -3) : $name;
134 if (empty($addressOptions[$nameWithoutID])) {
136 if (in_array($nameWithoutID, array(
137 'street_number', 'street_name', 'street_unit')) && !empty($addressOptions['street_address_parsing'])) {
146 $attributes = $attributes[$name];
149 //build normal select if country is not present in address block
150 if ($name == 'state_province_id' && !$addressOptions['country']) {
151 $select = 'stateProvince';
155 if ($name == 'country_id' ||
$name == 'state_province_id' ||
$name == 'county_id') {
156 if ($name == 'country_id') {
157 $stateCountryMap[$blockId]['country'] = "address_{$blockId}_{$name}";
158 $selectOptions = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::country();
160 elseif ($name == 'state_province_id') {
161 $stateCountryMap[$blockId]['state_province'] = "address_{$blockId}_{$name}";
162 if ($countryDefault) {
163 $selectOptions = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::stateProvinceForCountry($countryDefault);
166 $selectOptions = array('' => ts('- select a country -'));
169 elseif ($name == 'county_id') {
170 $stateCountryMap[$blockId]['county'] = "address_{$blockId}_{$name}";
171 if ($form->getSubmitValue("address[{$blockId}][state_province_id]")) {
172 $selectOptions = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::countyForState($form->getSubmitValue("address[{$blockId}][state_province_id]"));
174 elseif ($form->getSubmitValue("address[{$blockId}][county_id]")) {
175 $selectOptions = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::county();
178 $selectOptions = array('' => ts('- select a state -'));
181 $form->addElement('select',
182 "address[$blockId][$name]",
188 if ($name == 'address_name') {
192 $form->addElement('text',
193 "address[$blockId][$name]",
200 if ($name == 'state_province_id') {
201 $stateCountryMap[$blockId]['state_province'] = "address_{$blockId}_{$name}";
203 $form->addElement('select',
204 "address[$blockId][$name]",
206 array('' => ts('- select -')) + CRM_Core_PseudoConstant
::$select()
211 CRM_Core_BAO_Address
::addStateCountryMap($stateCountryMap);
214 if (!empty($form->_values
['address']) && !empty($form->_values
['address'][$blockId])) {
215 $entityId = $form->_values
['address'][$blockId]['id'];
218 // CRM-11665 geocode override option
220 if (!empty($config->geocodeMethod
)) {
222 $form->addElement('checkbox',
223 "address[$blockId][manual_geo_code]",
224 ts('Override automatic geocoding')
227 $form->assign('geoCode', $geoCode);
229 // Process any address custom data -
230 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Address',
235 if (isset($groupTree) && is_array($groupTree)) {
236 // use simplified formatted groupTree
237 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, $form);
239 // make sure custom fields are added /w element-name in the format - 'address[$blockId][custom-X]'
240 foreach ($groupTree as $id => $group) {
241 foreach ($group['fields'] as $fldId => $field) {
242 $groupTree[$id]['fields'][$fldId]['element_custom_name'] = $field['element_name'];
243 $groupTree[$id]['fields'][$fldId]['element_name'] = "address[$blockId][{$field['element_name']}]";
248 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $defaults);
250 // since we change element name for address custom data, we need to format the setdefault values
251 $addressDefaults = array();
252 foreach ($defaults as $key => $val) {
253 if ( empty( $val ) ) {
257 // inorder to set correct defaults for checkbox custom data, we need to converted flat key to array
258 // this works for all types custom data
259 $keyValues = explode('[', str_replace(']', '', $key));
260 $addressDefaults[$keyValues[0]][$keyValues[1]][$keyValues[2]] = $val;
263 $form->setDefaults($addressDefaults);
265 // we setting the prefix to 'dnc_' below, so that we don't overwrite smarty's grouptree var.
266 // And we can't set it to 'address_' because we want to set it in a slightly different format.
267 CRM_Core_BAO_CustomGroup
::buildQuickForm($form, $groupTree, FALSE, 'dnc_');
269 // during contact editing : if no address is filled
270 // required custom data must not produce 'required' form rule error
271 // more handling done in formRule func
273 CRM_Contact_Form_Edit_Address
::storeRequiredCustomDataInfo($form, $groupTree);
276 $template = CRM_Core_Smarty
::singleton();
277 $tplGroupTree = $template->get_template_vars('address_groupTree');
278 $tplGroupTree = empty($tplGroupTree) ?
array(
281 $form->assign('address_groupTree', $tplGroupTree +
array($blockId => $groupTree));
282 // unset the temp smarty var that got created
283 $form->assign('dnc_groupTree', NULL);
285 // address custom data processing ends ..
289 $form->addElement('checkbox', "address[$blockId][use_shared_address]", NULL, ts('Use another contact\'s address'));
291 // Override the default profile links to add address form
292 $profileLinks = CRM_Core_BAO_UFGroup
::getCreateLinks(array('new_individual', 'new_organization', 'new_household'), 'shared_address');
293 $form->addEntityRef("address[$blockId][master_contact_id]", ts('Share With'), array('create' => $profileLinks));
298 * check for correct state / country mapping.
300 * @param array reference $fields - submitted form values.
301 * @param array reference $errors - if any errors found add to this array. please.
303 * @return true if no errors
304 * array of errors if any present.
309 static function formRule($fields, $files, $self) {
312 $customDataRequiredFields = array();
313 if ($self && property_exists($self, '_addressRequireOmission')) {
314 $customDataRequiredFields = explode(',', $self->_addressRequireOmission
);
317 // check for state/county match if not report error to user.
318 if (!empty($fields['address']) && is_array($fields['address'])) {
319 foreach ($fields['address'] as $instance => $addressValues) {
321 if (CRM_Utils_System
::isNull($addressValues)) {
322 // DETACH 'required' form rule error to
323 // custom data only if address data not exists upon submission
324 if (!empty($customDataRequiredFields)) {
325 foreach($customDataRequiredFields as $customElementName) {
326 $elementName = "address[$instance][$customElementName]";
327 if ($self->getElementError($elementName)) {
328 // set element error to none
329 $self->setElementError($elementName, NULL);
336 // DETACH 'required' form rule error to
337 // custom data only if address data not exists upon submission
338 if (!empty($customDataRequiredFields) && !CRM_Core_BAO_Address
::dataExists($addressValues)) {
339 foreach($customDataRequiredFields as $customElementName) {
340 $elementName = "address[$instance][$customElementName]";
341 if ($self->getElementError($elementName)) {
342 // set element error to none
343 $self->setElementError($elementName, NULL);
348 $countryId = CRM_Utils_Array
::value('country_id', $addressValues);
350 $stateProvinceId = CRM_Utils_Array
::value('state_province_id', $addressValues);
352 //do check for mismatch countries
353 if ($stateProvinceId && $countryId) {
354 $stateProvinceDAO = new CRM_Core_DAO_StateProvince();
355 $stateProvinceDAO->id
= $stateProvinceId;
356 $stateProvinceDAO->find(TRUE);
357 if ($stateProvinceDAO->country_id
!= $countryId) {
358 // countries mismatch hence display error
359 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
360 $countries = CRM_Core_PseudoConstant
::country();
361 $errors["address[$instance][state_province_id]"] = ts('State/Province %1 is not part of %2. It belongs to %3.',
363 1 => $stateProvinces[$stateProvinceId],
364 2 => $countries[$countryId],
365 3 => $countries[$stateProvinceDAO->country_id
]
371 $countyId = CRM_Utils_Array
::value('county_id', $addressValues);
373 //state county validation
374 if ($stateProvinceId && $countyId) {
375 $countyDAO = new CRM_Core_DAO_County();
376 $countyDAO->id
= $countyId;
377 $countyDAO->find(TRUE);
378 if ($countyDAO->state_province_id
!= $stateProvinceId) {
379 $counties = CRM_Core_PseudoConstant
::county();
380 $errors["address[$instance][county_id]"] = ts('County %1 is not part of %2. It belongs to %3.',
382 1 => $counties[$countyId],
383 2 => $stateProvinces[$stateProvinceId],
384 3 => $stateProvinces[$countyDAO->state_province_id
]
390 if (!empty($addressValues['use_shared_address']) && empty($addressValues['master_id'])) {
391 $errors["address[$instance][use_shared_address]"] = ts('Please select valid shared contact or a contact with valid address.');
396 return empty($errors) ?
TRUE : $errors;
399 static function fixStateSelect(&$form,
403 $countryDefaultValue,
404 $stateDefaultValue = NULL
406 $countryID = $stateID = NULL;
407 if (isset($form->_elementIndex
[$countryElementName])) {
408 //get the country id to load states -
409 //first check for submitted value,
410 //then check for user passed value.
411 //finally check for element default val.
412 $submittedVal = $form->getSubmitValue($countryElementName);
414 $countryID = $submittedVal;
416 elseif ($countryDefaultValue) {
417 $countryID = $countryDefaultValue;
420 $countryID = CRM_Utils_Array
::value(0, $form->getElementValue($countryElementName));
423 $stateTitle = ts('State/Province');
424 if (isset($form->_fields
[$stateElementName]['title'])) {
425 $stateTitle = $form->_fields
[$stateElementName]['title'];
428 if (isset($form->_elementIndex
[$stateElementName])) {
429 $submittedValState = $form->getSubmitValue($stateElementName);
430 if ($submittedValState) {
431 $stateID = $submittedValState;
433 elseif ($stateDefaultValue) {
434 $stateID = $stateDefaultValue;
437 $stateID = CRM_Utils_Array
::value(0, $form->getElementValue($stateElementName));
441 if (isset($form->_elementIndex
[$stateElementName])) {
443 $stateProvinces = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
446 $stateProvinces = CRM_Core_PseudoConstant
::stateProvince();
449 $stateSelect = & $form->addElement('select', $stateElementName, $stateTitle,
450 array('' => ts('- select -')) +
$stateProvinces);
453 if (isset($form->_elementIndex
[$stateElementName]) && isset($form->_elementIndex
[$countyElementName])) {
455 $counties = CRM_Core_PseudoConstant
::countyForState($stateID);
458 $counties = CRM_Core_PseudoConstant
::county();
461 $form->addElement('select', $countyElementName, ts('County'), array('' => ts('- select -')) +
$counties);
464 // CRM-7296 freeze the select for state if address is shared with household
465 // CRM-9070 freeze the select for state if it is view only
466 if (isset($form->_fields
) && !empty($form->_fields
[$stateElementName]) &&
467 (!empty($form->_fields
[$stateElementName]['is_shared']) ||
!empty($form->_fields
[$stateElementName]['is_view']))
469 $stateSelect->freeze();
474 * function to set default values for address block
476 * @param array $defaults defaults associated array
477 * @param object $form form object
482 static function setDefaultValues( &$defaults, &$form ) {
483 $addressValues = array();
484 if (isset($defaults['address']) && is_array($defaults['address']) &&
485 !CRM_Utils_System
::isNull($defaults['address'])
488 // start of contact shared adddress defaults
489 $sharedAddresses = array();
490 $masterAddress = array();
492 // get contact name of shared contact names
493 $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils
::getAddressShareContactNames($defaults['address']);
495 foreach ($defaults['address'] as $key => $addressValue) {
496 if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) {
497 $sharedAddresses[$key]['shared_address_display'] = array(
498 'address' => $addressValue['display'],
499 'name' => $shareAddressContactNames[$addressValue['master_id']]['name'],
503 $defaults['address'][$key]['use_shared_address'] = 0;
506 //check if any address is shared by any other contacts
507 $masterAddress[$key] = CRM_Core_BAO_Address
::checkContactSharedAddress($addressValue['id']);
510 $form->assign('sharedAddresses', $sharedAddresses);
511 $form->assign('masterAddress', $masterAddress);
512 // end of shared address defaults
514 // start of parse address functionality
515 // build street address, CRM-5450.
516 if ($form->_parseStreetAddress
) {
517 $parseFields = array('street_address', 'street_number', 'street_name', 'street_unit');
518 foreach ($defaults['address'] as $cnt => & $address) {
519 $streetAddress = NULL;
521 'street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) {
522 if (in_array($fld, array(
523 'street_name', 'street_unit'))) {
524 $streetAddress .= ' ';
526 $streetAddress .= CRM_Utils_Array
::value($fld, $address);
528 $streetAddress = trim($streetAddress);
529 if (!empty($streetAddress)) {
530 $address['street_address'] = $streetAddress;
532 if (isset($address['street_number'])) {
533 $address['street_number'] .= CRM_Utils_Array
::value('street_number_suffix', $address);
536 // build array for set default.
537 foreach ($parseFields as $field) {
538 $addressValues["{$field}_{$cnt}"] = CRM_Utils_Array
::value($field, $address);
540 // don't load fields, use js to populate.
541 foreach (array('street_number', 'street_name', 'street_unit') as $f) {
542 if (isset($address[$f])) {
547 $form->assign('allAddressFieldValues', json_encode($addressValues));
549 //hack to handle show/hide address fields.
550 $parsedAddress = array();
551 if ($form->_contactId
&& !empty($_POST['address']) && is_array($_POST['address'])
553 foreach ($_POST['address'] as $cnt => $values) {
554 $showField = 'streetAddress';
555 foreach (array('street_number', 'street_name', 'street_unit') as $fld) {
556 if (!empty($values[$fld])) {
557 $showField = 'addressElements';
561 $parsedAddress[$cnt] = $showField;
564 $form->assign('showHideAddressFields', $parsedAddress);
565 $form->assign('loadShowHideAddressFields', empty($parsedAddress) ?
FALSE : TRUE);
567 // end of parse address functionality
572 static function storeRequiredCustomDataInfo(&$form, $groupTree) {
573 if (CRM_Utils_System
::getClassName($form) == 'CRM_Contact_Form_Contact') {
574 $requireOmission = NULL;
575 foreach ($groupTree as $csId => $csVal) {
576 // only process Address entity fields
577 if ($csVal['extends'] != 'Address') {
581 foreach ($csVal['fields'] as $cdId => $cdVal) {
582 if ($cdVal['is_required']) {
583 $elementName = $cdVal['element_name'];
584 if (in_array($elementName, $form->_required
)) {
585 // store the omitted rule for a element, to be used later on
586 $requireOmission .= $cdVal['element_custom_name'] . ',';
592 $form->_addressRequireOmission
= rtrim($requireOmission, ',');