Ian province abbreviation patch - issue 724
[civicrm-core.git] / CRM / Contact / Form / Edit / Address.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33
34 /**
35 * This class is used to build address block.
36 */
37 class CRM_Contact_Form_Edit_Address {
38
39 /**
40 * Build form for address input fields.
41 *
42 * @param CRM_Core_Form $form
43 * @param int $addressBlockCount
44 * The index of the address array (if multiple addresses on a page).
45 * @param bool $sharing
46 * False, if we want to skip the address sharing features.
47 * @param bool $inlineEdit
48 * True when edit used in inline edit.
49 */
50 public static function buildQuickForm(&$form, $addressBlockCount = NULL, $sharing = TRUE, $inlineEdit = FALSE) {
51 // passing this via the session is AWFUL. we need to fix this
52 if (!$addressBlockCount) {
53 $blockId = ($form->get('Address_Block_Count')) ? $form->get('Address_Block_Count') : 1;
54 }
55 else {
56 $blockId = $addressBlockCount;
57 }
58
59 $config = CRM_Core_Config::singleton();
60 $countryDefault = $config->defaultContactCountry;
61
62 $form->applyFilter('__ALL__', 'trim');
63
64 $js = array();
65 if (!$inlineEdit) {
66 $js = array('onChange' => 'checkLocation( this.id );', 'placeholder' => NULL);
67 }
68
69 //make location type required for inline edit
70 $form->addField("address[$blockId][location_type_id]", array('entity' => 'address', 'class' => 'eight') + $js, $inlineEdit);
71
72 if (!$inlineEdit) {
73 $js = array('id' => 'Address_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );');
74 }
75
76 $form->addField(
77 "address[$blockId][is_primary]", array(
78 'entity' => 'address',
79 'label' => ts('Primary location for this contact'),
80 'text' => ts('Primary location for this contact')) + $js);
81
82 if (!$inlineEdit) {
83 $js = array('id' => 'Address_' . $blockId . '_IsBilling', 'onClick' => 'singleSelect( this.id );');
84 }
85
86 $form->addField(
87 "address[$blockId][is_billing]", array(
88 'entity' => 'address',
89 'label' => ts('Primary location for this contact'),
90 'text' => ts('Primary location for this contact')) + $js);
91
92 // hidden element to store master address id
93 $form->addField("address[$blockId][master_id]", array('entity' => 'address', 'type' => 'hidden'));
94 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
95 'address_options', TRUE, NULL, TRUE
96 );
97 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Address');
98
99 $elements = array(
100 'address_name',
101 'street_address',
102 'supplemental_address_1',
103 'supplemental_address_2',
104 'city',
105 'postal_code',
106 'postal_code_suffix',
107 'country_id',
108 'state_province_id',
109 'county_id',
110 'geo_code_1',
111 'geo_code_2',
112 'street_number',
113 'street_name',
114 'street_unit',
115 );
116
117 foreach ($elements as $name) {
118 //Remove id from name, to allow comparison against enabled addressOtions.
119 $nameWithoutID = strpos($name, '_id') !== FALSE ? substr($name, 0, -3) : $name;
120 // Skip fields which are not enabled in the address options.
121 if (empty($addressOptions[$nameWithoutID])) {
122 $continue = TRUE;
123 //Don't skip street parsed fields when parsing is enabled.
124 if (in_array($nameWithoutID, array(
125 'street_number',
126 'street_name',
127 'street_unit',
128 )) && !empty($addressOptions['street_address_parsing'])
129 ) {
130 $continue = FALSE;
131 }
132 if ($continue) {
133 continue;
134 }
135 }
136 if ($name == 'address_name') {
137 $name = 'name';
138 }
139
140 $params = array('entity' => 'address');
141
142 if ($name == 'postal_code_suffix') {
143 $params['label'] = ts('Suffix');
144 }
145
146 $form->addField("address[$blockId][$name]", $params);
147 }
148
149 $entityId = NULL;
150 if (!empty($form->_values['address']) && !empty($form->_values['address'][$blockId])) {
151 $entityId = $form->_values['address'][$blockId]['id'];
152 }
153
154 // CRM-11665 geocode override option
155 $geoCode = FALSE;
156 if (!empty($config->geocodeMethod)) {
157 $geoCode = TRUE;
158 $form->addElement('checkbox',
159 "address[$blockId][manual_geo_code]",
160 ts('Override automatic geocoding')
161 );
162 }
163 $form->assign('geoCode', $geoCode);
164
165 // Process any address custom data -
166 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Address',
167 $form,
168 $entityId
169 );
170
171 if (isset($groupTree) && is_array($groupTree)) {
172 // use simplified formatted groupTree
173 $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, $form);
174
175 // make sure custom fields are added /w element-name in the format - 'address[$blockId][custom-X]'
176 foreach ($groupTree as $id => $group) {
177 foreach ($group['fields'] as $fldId => $field) {
178 $groupTree[$id]['fields'][$fldId]['element_custom_name'] = $field['element_name'];
179 $groupTree[$id]['fields'][$fldId]['element_name'] = "address[$blockId][{$field['element_name']}]";
180 }
181 }
182
183 $defaults = array();
184 CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $defaults);
185
186 // since we change element name for address custom data, we need to format the setdefault values
187 $addressDefaults = array();
188 foreach ($defaults as $key => $val) {
189 if (empty($val)) {
190 continue;
191 }
192
193 // inorder to set correct defaults for checkbox custom data, we need to converted flat key to array
194 // this works for all types custom data
195 $keyValues = explode('[', str_replace(']', '', $key));
196 $addressDefaults[$keyValues[0]][$keyValues[1]][$keyValues[2]] = $val;
197 }
198
199 $form->setDefaults($addressDefaults);
200
201 // we setting the prefix to 'dnc_' below, so that we don't overwrite smarty's grouptree var.
202 // And we can't set it to 'address_' because we want to set it in a slightly different format.
203 CRM_Core_BAO_CustomGroup::buildQuickForm($form, $groupTree, FALSE, 'dnc_');
204
205 // during contact editing : if no address is filled
206 // required custom data must not produce 'required' form rule error
207 // more handling done in formRule func
208 if (!$inlineEdit) {
209 CRM_Contact_Form_Edit_Address::storeRequiredCustomDataInfo($form, $groupTree);
210 }
211
212 $template = CRM_Core_Smarty::singleton();
213 $tplGroupTree = $template->get_template_vars('address_groupTree');
214 $tplGroupTree = empty($tplGroupTree) ? array() : $tplGroupTree;
215
216 $form->assign('address_groupTree', $tplGroupTree + array($blockId => $groupTree));
217 // unset the temp smarty var that got created
218 $form->assign('dnc_groupTree', NULL);
219 }
220 // address custom data processing ends ..
221
222 if ($sharing) {
223 // shared address
224 $form->addElement('checkbox', "address[$blockId][use_shared_address]", NULL, ts('Use another contact\'s address'));
225
226 // Override the default profile links to add address form
227 $profileLinks = CRM_Core_BAO_UFGroup::getCreateLinks(array(
228 'new_individual',
229 'new_organization',
230 'new_household',
231 ), 'shared_address');
232 $form->addEntityRef("address[$blockId][master_contact_id]", ts('Share With'), array('create' => $profileLinks));
233 }
234 }
235
236 /**
237 * Check for correct state / country mapping.
238 *
239 * @param array $fields
240 * @param array $files
241 * @param CRM_Core_Form $self
242 *
243 * @return array|bool
244 * if no errors
245 */
246 public static function formRule($fields, $files, $self) {
247 $errors = array();
248
249 $customDataRequiredFields = array();
250 if ($self && property_exists($self, '_addressRequireOmission')) {
251 $customDataRequiredFields = explode(',', $self->_addressRequireOmission);
252 }
253
254 if (!empty($fields['address']) && is_array($fields['address'])) {
255 foreach ($fields['address'] as $instance => $addressValues) {
256
257 if (CRM_Utils_System::isNull($addressValues)) {
258 // DETACH 'required' form rule error to
259 // custom data only if address data not exists upon submission
260 if (!empty($customDataRequiredFields)) {
261 foreach ($customDataRequiredFields as $customElementName) {
262 $elementName = "address[$instance][$customElementName]";
263 if ($self->getElementError($elementName)) {
264 // set element error to none
265 $self->setElementError($elementName, NULL);
266 }
267 }
268 }
269 continue;
270 }
271
272 // DETACH 'required' form rule error to
273 // custom data only if address data not exists upon submission
274 if (!empty($customDataRequiredFields) && !CRM_Core_BAO_Address::dataExists($addressValues)) {
275 foreach ($customDataRequiredFields as $customElementName) {
276 $elementName = "address[$instance][$customElementName]";
277 if ($self->getElementError($elementName)) {
278 // set element error to none
279 $self->setElementError($elementName, NULL);
280 }
281 }
282 }
283
284 if (!empty($addressValues['use_shared_address']) && empty($addressValues['master_id'])) {
285 $errors["address[$instance][use_shared_address]"] = ts('Please select valid shared contact or a contact with valid address.');
286 }
287 }
288 }
289
290 return empty($errors) ? TRUE : $errors;
291 }
292
293 /**
294 * Set default values for address block.
295 *
296 * @param array $defaults
297 * Defaults associated array.
298 * @param CRM_Core_Form $form
299 * Form object.
300 */
301 public static function setDefaultValues(&$defaults, &$form) {
302 $addressValues = array();
303 if (isset($defaults['address']) && is_array($defaults['address']) &&
304 !CRM_Utils_System::isNull($defaults['address'])
305 ) {
306
307 // start of contact shared adddress defaults
308 $sharedAddresses = array();
309 $masterAddress = array();
310
311 // get contact name of shared contact names
312 $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($defaults['address']);
313
314 foreach ($defaults['address'] as $key => $addressValue) {
315 if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) {
316 $master_cid = $shareAddressContactNames[$addressValue['master_id']]['contact_id'];
317 $sharedAddresses[$key]['shared_address_display'] = array(
318 'address' => $addressValue['display'],
319 'name' => $shareAddressContactNames[$addressValue['master_id']]['name'],
320 'options' => CRM_Core_BAO_Address::getValues(array(
321 'entity_id' => $master_cid,
322 'contact_id' => $master_cid,
323 )),
324 'master_id' => $addressValue['master_id'],
325 );
326 $defaults['address'][$key]['master_contact_id'] = $master_cid;
327 }
328 else {
329 $defaults['address'][$key]['use_shared_address'] = 0;
330 }
331
332 //check if any address is shared by any other contacts
333 $masterAddress[$key] = CRM_Core_BAO_Address::checkContactSharedAddress($addressValue['id']);
334 }
335
336 $form->assign('sharedAddresses', $sharedAddresses);
337 $form->assign('masterAddress', $masterAddress);
338 // end of shared address defaults
339
340 // start of parse address functionality
341 // build street address, CRM-5450.
342 if ($form->_parseStreetAddress) {
343 $parseFields = array('street_address', 'street_number', 'street_name', 'street_unit');
344 foreach ($defaults['address'] as $cnt => & $address) {
345 $streetAddress = NULL;
346 foreach (array(
347 'street_number',
348 'street_number_suffix',
349 'street_name',
350 'street_unit',
351 ) as $fld) {
352 if (in_array($fld, array(
353 'street_name',
354 'street_unit',
355 ))) {
356 $streetAddress .= ' ';
357 }
358 $streetAddress .= CRM_Utils_Array::value($fld, $address);
359 }
360 $streetAddress = trim($streetAddress);
361 if (!empty($streetAddress)) {
362 $address['street_address'] = $streetAddress;
363 }
364 if (isset($address['street_number'])) {
365 $address['street_number'] .= CRM_Utils_Array::value('street_number_suffix', $address);
366 }
367
368 // build array for set default.
369 foreach ($parseFields as $field) {
370 $addressValues["{$field}_{$cnt}"] = CRM_Utils_Array::value($field, $address);
371 }
372 // don't load fields, use js to populate.
373 foreach (array('street_number', 'street_name', 'street_unit') as $f) {
374 if (isset($address[$f])) {
375 unset($address[$f]);
376 }
377 }
378 }
379 $form->assign('allAddressFieldValues', json_encode($addressValues));
380
381 //hack to handle show/hide address fields.
382 $parsedAddress = array();
383 if ($form->_contactId && !empty($_POST['address']) && is_array($_POST['address'])
384 ) {
385 foreach ($_POST['address'] as $cnt => $values) {
386 $showField = 'streetAddress';
387 foreach (array('street_number', 'street_name', 'street_unit') as $fld) {
388 if (!empty($values[$fld])) {
389 $showField = 'addressElements';
390 break;
391 }
392 }
393 $parsedAddress[$cnt] = $showField;
394 }
395 }
396 $form->assign('showHideAddressFields', $parsedAddress);
397 $form->assign('loadShowHideAddressFields', empty($parsedAddress) ? FALSE : TRUE);
398 }
399 // end of parse address functionality
400 }
401 }
402
403 /**
404 * Store required custom data info.
405 *
406 * @param CRM_Core_Form $form
407 * @param array $groupTree
408 */
409 public static function storeRequiredCustomDataInfo(&$form, $groupTree) {
410 if (CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Contact') {
411 $requireOmission = NULL;
412 foreach ($groupTree as $csId => $csVal) {
413 // only process Address entity fields
414 if ($csVal['extends'] != 'Address') {
415 continue;
416 }
417
418 foreach ($csVal['fields'] as $cdId => $cdVal) {
419 if ($cdVal['is_required']) {
420 $elementName = $cdVal['element_name'];
421 if (in_array($elementName, $form->_required)) {
422 // store the omitted rule for a element, to be used later on
423 $requireOmission .= $cdVal['element_custom_name'] . ',';
424 }
425 }
426 }
427 }
428
429 $form->_addressRequireOmission = rtrim($requireOmission, ',');
430 }
431 }
432
433 }