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