3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class is used to build address block.
21 class CRM_Contact_Form_Edit_Address
{
24 * Build form for address input fields.
26 * @param CRM_Core_Form $form
27 * @param int $addressBlockCount
28 * The index of the address array (if multiple addresses on a page).
29 * @param bool $sharing
30 * False, if we want to skip the address sharing features.
31 * @param bool $inlineEdit
32 * True when edit used in inline edit.
34 * @throws \CiviCRM_API3_Exception
36 public static function buildQuickForm(&$form, $addressBlockCount = NULL, $sharing = TRUE, $inlineEdit = FALSE) {
37 // passing this via the session is AWFUL. we need to fix this
38 if (!$addressBlockCount) {
39 $blockId = ($form->get('Address_Block_Count')) ?
$form->get('Address_Block_Count') : 1;
42 $blockId = $addressBlockCount;
45 $form->applyFilter('__ALL__', 'trim');
49 $js = ['onChange' => 'checkLocation( this.id );', 'placeholder' => NULL];
52 //make location type required for inline edit
53 $form->addField("address[$blockId][location_type_id]", ['entity' => 'address', 'class' => 'eight', 'option_url' => NULL] +
$js, $inlineEdit);
55 $js = ['id' => 'Address_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );'];
59 "address[$blockId][is_primary]", [
60 'entity' => 'address',
62 'label' => ts('Primary location for this contact'),
63 'text' => ts('Primary location for this contact'),
67 $js = ['id' => 'Address_' . $blockId . '_IsBilling', 'onClick' => 'singleSelect( this.id );'];
71 "address[$blockId][is_billing]", [
72 'entity' => 'address',
73 'label' => ts('Billing location for this contact'),
74 'text' => ts('Billing location for this contact'),
77 // hidden element to store master address id
78 $form->addField("address[$blockId][master_id]", ['entity' => 'address', 'type' => 'hidden']);
79 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
80 'address_options', TRUE, NULL, TRUE
86 'supplemental_address_1',
87 'supplemental_address_2',
88 'supplemental_address_3',
102 foreach ($elements as $name) {
103 //Remove id from name, to allow comparison against enabled addressOptions.
104 $nameWithoutID = strpos($name, '_id') !== FALSE ?
substr($name, 0, -3) : $name;
105 // Skip fields which are not enabled in the address options.
106 if (empty($addressOptions[$nameWithoutID])) {
108 //Don't skip street parsed fields when parsing is enabled.
109 if (in_array($nameWithoutID, [
113 ]) && !empty($addressOptions['street_address_parsing'])) {
120 if ($name === 'address_name') {
124 $params = ['entity' => 'Address'];
126 if ($name === 'postal_code_suffix') {
127 $params['label'] = ts('Suffix');
130 $form->addField("address[$blockId][$name]", $params);
134 if (!empty($form->_values
['address']) && !empty($form->_values
['address'][$blockId])) {
135 $entityId = $form->_values
['address'][$blockId]['id'];
138 // CRM-11665 geocode override option
140 if (CRM_Utils_GeocodeProvider
::getUsableClassName()) {
142 $form->addElement('checkbox',
143 "address[$blockId][manual_geo_code]",
144 ts('Override automatic geocoding')
147 $form->assign('geoCode', $geoCode);
149 self
::addCustomDataToForm($form, $entityId, $blockId);
153 $form->addElement('checkbox', "address[$blockId][use_shared_address]", NULL, ts('Use another contact\'s address'));
155 // Override the default profile links to add address form
156 $profileLinks = CRM_Contact_BAO_Contact
::getEntityRefCreateLinks('shared_address');
157 $form->addEntityRef("address[$blockId][master_contact_id]", ts('Share With'), ['create' => $profileLinks, 'api' => ['extra' => ['contact_type']]]);
159 // do we want to update employer for shared address
160 $employer_label = '<span class="addrel-employer">' . ts('Set this organization as current employer') . '</span>';
161 $household_label = '<span class="addrel-household">' . ts('Create a household member relationship with this contact') . '</span>';
162 $form->addElement('checkbox', "address[$blockId][add_relationship]", NULL, $employer_label . $household_label);
167 * Check for correct state / country mapping.
169 * @param array $fields
170 * @param array $files
171 * @param CRM_Core_Form $self
176 public static function formRule($fields, $files = [], $self = NULL) {
179 $customDataRequiredFields = [];
180 if ($self && property_exists($self, '_addressRequireOmission')) {
181 $customDataRequiredFields = explode(',', $self->_addressRequireOmission
);
184 if (!empty($fields['address']) && is_array($fields['address'])) {
185 foreach ($fields['address'] as $instance => $addressValues) {
187 if (CRM_Utils_System
::isNull($addressValues)) {
188 // DETACH 'required' form rule error to
189 // custom data only if address data not exists upon submission
190 if (!empty($customDataRequiredFields)) {
191 foreach ($customDataRequiredFields as $customElementName) {
192 $elementName = "address[$instance][$customElementName]";
193 if ($self->getElementError($elementName)) {
194 // set element error to none
195 $self->setElementError($elementName, NULL);
202 // DETACH 'required' form rule error to
203 // custom data if address data not exists upon submission
204 // or if master address is selected
205 if (!empty($customDataRequiredFields) && (!CRM_Core_BAO_Address
::dataExists($addressValues) ||
!empty($addressValues['master_id']))) {
206 foreach ($customDataRequiredFields as $customElementName) {
207 $elementName = "address[$instance][$customElementName]";
208 if ($self->getElementError($elementName)) {
209 // set element error to none
210 $self->setElementError($elementName, NULL);
215 if (!empty($addressValues['use_shared_address']) && empty($addressValues['master_id'])) {
216 $errors["address[$instance][use_shared_address]"] = ts('Please select valid shared contact or a contact with valid address.');
221 return empty($errors) ?
TRUE : $errors;
225 * Set default values for address block.
227 * @param array $defaults
228 * Defaults associated array.
229 * @param CRM_Core_Form $form
232 public static function setDefaultValues(&$defaults, &$form) {
234 // Actual values will be assigned to these below if there are some.
235 $form->assign('masterAddress');
236 $form->assign('sharedAddresses', []);
237 if (isset($defaults['address']) && is_array($defaults['address']) &&
238 !CRM_Utils_System
::isNull($defaults['address'])
241 // start of contact shared adddress defaults
242 $sharedAddresses = [];
245 // get contact name of shared contact names
246 $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils
::getAddressShareContactNames($defaults['address']);
248 foreach ($defaults['address'] as $key => $addressValue) {
249 if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) {
250 $master_cid = $shareAddressContactNames[$addressValue['master_id']]['contact_id'];
251 $sharedAddresses[$key]['shared_address_display'] = [
252 'address' => $addressValue['display'],
253 'name' => $shareAddressContactNames[$addressValue['master_id']]['name'],
254 'options' => CRM_Core_BAO_Address
::getValues([
255 'entity_id' => $master_cid,
256 'contact_id' => $master_cid,
258 'master_id' => $addressValue['master_id'],
260 $defaults['address'][$key]['master_contact_id'] = $master_cid;
263 $defaults['address'][$key]['use_shared_address'] = 0;
266 //check if any address is shared by any other contacts
267 $masterAddress[$key] = CRM_Core_BAO_Address
::checkContactSharedAddress($addressValue['id']);
270 $form->assign('sharedAddresses', $sharedAddresses);
271 $form->assign('masterAddress', $masterAddress);
272 // end of shared address defaults
274 // start of parse address functionality
275 // build street address, CRM-5450.
276 if ($form->_parseStreetAddress
) {
277 $parseFields = ['street_address', 'street_number', 'street_name', 'street_unit'];
278 foreach ($defaults['address'] as $cnt => & $address) {
279 $streetAddress = NULL;
282 'street_number_suffix',
290 $streetAddress .= ' ';
292 // CRM-17619 - if the street number suffix begins with a number, add a space
293 $numsuffix = $address[$fld] ??
NULL;
294 if ($fld === 'street_number_suffix' && !empty($numsuffix)) {
295 if (ctype_digit(substr($numsuffix, 0, 1))) {
296 $streetAddress .= ' ';
299 $streetAddress .= CRM_Utils_Array
::value($fld, $address);
301 $streetAddress = trim($streetAddress);
302 if (!empty($streetAddress)) {
303 $address['street_address'] = $streetAddress;
305 if (isset($address['street_number'])) {
306 // CRM-17619 - if the street number suffix begins with a number, add a space
307 $thesuffix = $address['street_number_suffix'] ??
NULL;
309 if (ctype_digit(substr($thesuffix, 0, 1))) {
310 $address['street_number'] .= " ";
313 $address['street_number'] .= $thesuffix;
315 // build array for set default.
316 foreach ($parseFields as $field) {
317 $addressValues["{$field}_{$cnt}"] = $address[$field] ??
NULL;
319 // don't load fields, use js to populate.
320 foreach (['street_number', 'street_name', 'street_unit'] as $f) {
321 if (isset($address[$f])) {
326 $form->assign('allAddressFieldValues', json_encode($addressValues));
328 //hack to handle show/hide address fields.
330 if ($form->_contactId
&& !empty($_POST['address']) && is_array($_POST['address'])
332 foreach ($_POST['address'] as $cnt => $values) {
333 $showField = 'streetAddress';
334 foreach (['street_number', 'street_name', 'street_unit'] as $fld) {
335 if (!empty($values[$fld])) {
336 $showField = 'addressElements';
340 $parsedAddress[$cnt] = $showField;
343 $form->assign('showHideAddressFields', $parsedAddress);
344 $form->assign('loadShowHideAddressFields', !empty($parsedAddress));
346 // end of parse address functionality
351 * Store required custom data info.
353 * @param CRM_Core_Form $form
354 * @param array $groupTree
356 public static function storeRequiredCustomDataInfo(&$form, $groupTree) {
357 if (in_array(CRM_Utils_System
::getClassName($form), ['CRM_Contact_Form_Contact', 'CRM_Contact_Form_Inline_Address'])) {
358 $requireOmission = NULL;
359 foreach ($groupTree as $csId => $csVal) {
360 // only process Address entity fields
361 if ($csVal['extends'] !== 'Address') {
365 foreach ($csVal['fields'] as $cdId => $cdVal) {
366 if (!empty($cdVal['is_required'])) {
367 $elementName = $cdVal['element_name'];
368 if (in_array($elementName, $form->_required
)) {
369 // store the omitted rule for a element, to be used later on
370 $requireOmission .= $cdVal['element_custom_name'] . ',';
376 $form->_addressRequireOmission
= rtrim($requireOmission, ',');
381 * Add custom data to the form.
383 * @param CRM_Core_Form $form
384 * @param int $entityId
385 * @param int $blockId
387 * @throws \CRM_Core_Exception
388 * @throws \CiviCRM_API3_Exception
390 protected static function addCustomDataToForm(&$form, $entityId, $blockId) {
391 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Address', NULL, $entityId);
393 if (isset($groupTree) && is_array($groupTree)) {
394 // use simplified formatted groupTree
395 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, $form);
397 // make sure custom fields are added /w element-name in the format - 'address[$blockId][custom-X]'
398 foreach ($groupTree as $id => $group) {
399 foreach ($group['fields'] as $fldId => $field) {
400 $groupTree[$id]['fields'][$fldId]['element_custom_name'] = $field['element_name'];
401 $groupTree[$id]['fields'][$fldId]['element_name'] = "address[$blockId][{$field['element_name']}]";
406 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $defaults);
408 // since we change element name for address custom data, we need to format the setdefault values
409 $addressDefaults = [];
410 foreach ($defaults as $key => $val) {
415 // in order to set correct defaults for checkbox custom data, we need to converted flat key to array
416 // this works for all types custom data
417 $keyValues = explode('[', str_replace(']', '', $key));
418 $addressDefaults[$keyValues[0]][$keyValues[1]][$keyValues[2]] = $val;
421 $form->setDefaults($addressDefaults);
423 // we setting the prefix to 'dnc_' below, so that we don't overwrite smarty's grouptree var.
424 // And we can't set it to 'address_' because we want to set it in a slightly different format.
425 CRM_Core_BAO_CustomGroup
::buildQuickForm($form, $groupTree, FALSE, 'dnc_');
427 // during contact editing : if no address is filled
428 // required custom data must not produce 'required' form rule error
429 // more handling done in formRule func
430 CRM_Contact_Form_Edit_Address
::storeRequiredCustomDataInfo($form, $groupTree);
432 $tplGroupTree = CRM_Core_Smarty
::singleton()
433 ->get_template_vars('address_groupTree');
434 $tplGroupTree = empty($tplGroupTree) ?
[] : $tplGroupTree;
436 $form->assign('address_groupTree', $tplGroupTree +
[$blockId => $groupTree]);
437 // unset the temp smarty var that got created
438 $form->assign('dnc_groupTree', NULL);
440 // address custom data processing ends ..