APIv4 - Add Address::getCoordinates action
[civicrm-core.git] / CRM / Core / Form / Renderer.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18require_once 'HTML/QuickForm/Renderer/ArraySmarty.php';
19
20/**
3c7fd868 21 * Customize QF output to meet our specific requirements
6a488035
TO
22 */
23class CRM_Core_Form_Renderer extends HTML_QuickForm_Renderer_ArraySmarty {
24
25 /**
26 * We only need one instance of this object. So we use the singleton
27 * pattern and cache the instance in this variable
28 *
29 * @var object
6a488035
TO
30 */
31 static private $_singleton = NULL;
32
33 /**
fe482240 34 * The converter from array size to css class.
6a488035
TO
35 *
36 * @var array
6a488035 37 */
518fa0ee 38 public static $_sizeMapper = [
6a488035
TO
39 2 => 'two',
40 4 => 'four',
41 6 => 'six',
42 8 => 'eight',
43 12 => 'twelve',
44 20 => 'medium',
45 30 => 'big',
46 45 => 'huge',
be2fb01f 47 ];
6a488035
TO
48
49 /**
fe482240 50 * Constructor.
95ea96be 51 */
317fceb4 52 public function __construct() {
6a488035
TO
53 $template = CRM_Core_Smarty::singleton();
54 parent::__construct($template);
55 }
56
57 /**
58 * Static instance provider.
59 *
60 * Method providing static instance of as in Singleton pattern.
61 */
00be9182 62 public static function &singleton() {
6a488035
TO
63 if (!isset(self::$_singleton)) {
64 self::$_singleton = new CRM_Core_Form_Renderer();
65 }
66 return self::$_singleton;
67 }
68
69 /**
fe482240 70 * Creates an array representing an element containing.
6a488035
TO
71 * the key for storing this. We allow the parent to do most of the
72 * work, but then we add some CiviCRM specific enhancements to
73 * make the html compliant with our css etc
74 *
6a488035 75 *
3c7fd868
CW
76 * @param HTML_QuickForm_element $element
77 * @param bool $required
78 * Whether an element is required.
79 * @param string $error
80 * Error associated with the element.
6a488035
TO
81 *
82 * @return array
83 */
00be9182 84 public function _elementToArray(&$element, $required, $error) {
6a488035
TO
85 self::updateAttributes($element, $required, $error);
86
87 $el = parent::_elementToArray($element, $required, $error);
88
89 // add label html
90 if (!empty($el['label'])) {
91 $id = $element->getAttribute('id');
92 if (!empty($id)) {
93 $el['label'] = '<label for="' . $id . '">' . $el['label'] . '</label>';
94 }
95 else {
96 $el['label'] = "<label>{$el['label']}</label>";
97 }
98 }
99
4a143c04 100 // Display-only (frozen) elements
704d3260 101 if (!empty($el['frozen'])) {
549be786 102 if ($element->getAttribute('data-api-entity') && $element->getAttribute('data-entity-value')) {
704d3260
CW
103 $this->renderFrozenEntityRef($el, $element);
104 }
b733747a
CW
105 elseif ($element->getAttribute('type') == 'text' && $element->getAttribute('data-select-params')) {
106 $this->renderFrozenSelect2($el, $element);
107 }
09edd4bd
CW
108 elseif ($element->getAttribute('type') == 'text' && $element->getAttribute('data-crm-datepicker')) {
109 $this->renderFrozenDatepicker($el, $element);
110 }
69b1c921 111 elseif ($element->getAttribute('type') == 'text' && $element->getAttribute('formatType')) {
b691052b 112 list($date, $time) = CRM_Utils_Date::setDateDefaults($element->getValue(), $element->getAttribute('formatType'), $element->getAttribute('format'), $element->getAttribute('timeformat'));
113 $date .= ($element->getAttribute('timeformat')) ? " $time" : '';
114 $el['html'] = $date . '<input type="hidden" value="' . $element->getValue() . '" name="' . $element->getAttribute('name') . '">';
657cae7c 115 }
720cfc38
CW
116 // Render html for wysiwyg textareas
117 if ($el['type'] == 'textarea' && isset($element->_attributes['class']) && strstr($element->_attributes['class'], 'wysiwyg')) {
118 $el['html'] = '<span class="crm-frozen-field">' . $el['value'] . '</span>';
699728cc
JM
119 }
120 else {
864005df
JM
121 $el['html'] = '<span class="crm-frozen-field">' . $el['html'] . '</span>';
122 }
704d3260 123 }
4a143c04
CW
124 // Active form elements
125 else {
be2fb01f 126 $typesToShowEditLink = ['select', 'group'];
3ef93345
MD
127 $hasEditPath = NULL !== $element->getAttribute('data-option-edit-path');
128
129 if (in_array($element->getType(), $typesToShowEditLink) && $hasEditPath) {
4a143c04
CW
130 $this->addOptionsEditLink($el, $element);
131 }
132
0c6fe5b5 133 if ($element->getAttribute('allowClear')) {
4a143c04
CW
134 $this->appendUnselectButton($el, $element);
135 }
136 }
704d3260 137
6a488035
TO
138 return $el;
139 }
140
141 /**
142 * Update the attributes of this element and add a few CiviCRM
143 * based attributes so we can style this form element better
144 *
6a488035 145 *
3c7fd868
CW
146 * @param HTML_QuickForm_element $element
147 * @param bool $required
148 * Whether an element is required.
149 * @param string $error
150 * Error associated with the element.
6a488035 151 *
6a488035 152 */
00be9182 153 public static function updateAttributes(&$element, $required, $error) {
6a488035
TO
154 // lets create an id for all input elements, so we can generate nice label tags
155 // to make it nice and clean, we'll just use the elementName if it is non null
be2fb01f 156 $attributes = [];
6a488035
TO
157 if (!$element->getAttribute('id')) {
158 $name = $element->getAttribute('name');
159 if ($name) {
be2fb01f
CW
160 $attributes['id'] = str_replace([']', '['],
161 ['', '_'],
6a488035
TO
162 $name
163 );
164 }
165 }
166
167 $class = $element->getAttribute('class');
168 $type = $element->getType();
c5b53a6f 169 if (!$class) {
e9bc5dcc 170 if ($type == 'text' || $type == 'password') {
6a488035
TO
171 $size = $element->getAttribute('size');
172 if (!empty($size)) {
9c1bc317 173 $class = self::$_sizeMapper[$size] ?? NULL;
6a488035
TO
174 }
175 }
176 }
177
4f95329c
CW
178 if ($type == 'select' && $element->getAttribute('multiple')) {
179 $type = 'multiselect';
180 }
76ec9ca7
CW
181 // Add widget-specific class
182 if (!$class || strpos($class, 'crm-form-') === FALSE) {
183 $class = ($class ? "$class " : '') . 'crm-form-' . $type;
184 }
75f59466
CW
185 elseif (strpos($class, 'crm-form-entityref') !== FALSE) {
186 self::preProcessEntityRef($element);
187 }
06508628
CW
188 elseif (strpos($class, 'crm-form-contact-reference') !== FALSE) {
189 self::preprocessContactReference($element);
190 }
d8f1758d
CW
191 // Hack to support html5 fields (number, url, etc)
192 else {
193 foreach (CRM_Core_Form::$html5Types as $type) {
194 if (strpos($class, "crm-form-$type") !== FALSE) {
195 $element->setAttribute('type', $type);
196 // Also add the "base" class for consistent styling
197 $class .= ' crm-form-text';
198 break;
199 }
200 }
092cb9c5 201 }
c5b53a6f 202
6a488035
TO
203 if ($required) {
204 $class .= ' required';
205 }
206
207 if ($error) {
208 $class .= ' error';
209 }
210
211 $attributes['class'] = $class;
212 $element->updateAttributes($attributes);
213 }
704d3260 214
75f59466 215 /**
fe482240 216 * Convert IDs to values and format for display.
06508628 217 *
3c7fd868 218 * @param HTML_QuickForm_element $field
75f59466 219 */
00be9182 220 public static function preProcessEntityRef($field) {
75f59466 221 $val = $field->getValue();
a8809160
CW
222 // Temporarily convert string values to an array
223 if (!is_array($val)) {
224 // Try to auto-detect method of serialization
225 $val = strpos($val, ',') ? explode(',', str_replace(', ', ',', $val)) : (array) CRM_Utils_Array::explodePadded($val);
75f59466
CW
226 }
227 if ($val) {
228 $entity = $field->getAttribute('data-api-entity');
e6d37e50
CW
229 // Get api params, ensure it is an array
230 $params = $field->getAttribute('data-api-params');
be2fb01f
CW
231 $params = $params ? json_decode($params, TRUE) : [];
232 $result = civicrm_api3($entity, 'getlist', ['id' => $val] + $params);
f39fa315
SL
233 // Purify label output of entityreference fields
234 if (!empty($result['values'])) {
235 foreach ($result['values'] as &$res) {
236 if (!empty($res['label'])) {
237 $res['label'] = CRM_Utils_String::purifyHTML($res['label']);
238 }
239 }
240 }
75f59466 241 if ($field->isFrozen()) {
a8809160 242 // Prevent js from treating frozen entityRef as a "live" field
75f59466
CW
243 $field->removeAttribute('class');
244 }
245 if (!empty($result['values'])) {
75f59466
CW
246 $field->setAttribute('data-entity-value', json_encode($result['values']));
247 }
a8809160
CW
248 // CRM-15803 - Remove invalid values
249 $val = array_intersect($val, CRM_Utils_Array::collect('id', $result['values']));
75f59466 250 }
a8809160
CW
251 // Convert array values back to a string
252 $field->setValue(implode(',', $val));
75f59466
CW
253 }
254
09edd4bd
CW
255 /**
256 * Render datepicker as text.
257 *
258 * @param array $el
259 * @param HTML_QuickForm_element $field
260 */
261 public function renderFrozenDatepicker(&$el, $field) {
262 $settings = json_decode($field->getAttribute('data-crm-datepicker'), TRUE);
263 $settings += ['date' => TRUE, 'time' => TRUE];
264 $val = $field->getValue();
265 if ($val) {
266 $dateFormat = NULL;
267 if (!$settings['time']) {
268 $val = substr($val, 0, 10);
269 }
270 elseif (!$settings['date']) {
271 $dateFormat = Civi::settings()->get('dateformatTime');
272 }
273 $val = CRM_Utils_Date::customFormat($val, $dateFormat);
274 }
275 $el['html'] = $val . '<input type="hidden" value="' . $field->getValue() . '" name="' . $field->getAttribute('name') . '">';
276 }
277
b733747a
CW
278 /**
279 * Render select2 as text.
280 *
281 * @param array $el
282 * @param HTML_QuickForm_element $field
283 */
284 public function renderFrozenSelect2(&$el, $field) {
285 $params = json_decode($field->getAttribute('data-select-params'), TRUE);
286 $val = $field->getValue();
287 if ($val && !empty($params['data'])) {
be2fb01f 288 $display = [];
b733747a
CW
289 foreach (explode(',', $val) as $item) {
290 $match = CRM_Utils_Array::findInTree($item, $params['data']);
291 if (isset($match['text']) && strlen($match['text'])) {
eb6f5055 292 $display[] = CRM_Utils_String::purifyHTML($match['text']);
b733747a
CW
293 }
294 }
295 $el['html'] = implode('; ', $display) . '<input type="hidden" value="' . $field->getValue() . '" name="' . $field->getAttribute('name') . '">';
296 }
297 }
298
704d3260
CW
299 /**
300 * Render entity references as text.
b56fec55 301 * If user has permission, format as link (for now limited to contacts).
3c7fd868
CW
302 *
303 * @param array $el
304 * @param HTML_QuickForm_element $field
704d3260 305 */
00be9182 306 public function renderFrozenEntityRef(&$el, $field) {
2229cf4f 307 $entity = $field->getAttribute('data-api-entity');
704d3260 308 $vals = json_decode($field->getAttribute('data-entity-value'), TRUE);
be2fb01f 309 $display = [];
a9b69e9f
CW
310
311 // Custom fields of type contactRef store their data in a slightly different format
2229cf4f 312 if ($field->getAttribute('data-crm-custom') && $entity == 'Contact') {
be2fb01f 313 $vals = [['id' => $vals['id'], 'label' => $vals['text']]];
a9b69e9f
CW
314 }
315
704d3260
CW
316 foreach ($vals as $val) {
317 // Format contact as link
2229cf4f 318 if ($entity == 'Contact' && CRM_Contact_BAO_Contact_Permission::allow($val['id'], CRM_Core_Permission::VIEW)) {
be2fb01f 319 $url = CRM_Utils_System::url("civicrm/contact/view", ['reset' => 1, 'cid' => $val['id']]);
41cb88ce 320 $val['label'] = '<a class="view-contact no-popup" href="' . $url . '" title="' . ts('View Contact') . '">' . CRM_Utils_String::purifyHTML($val['label']) . '</a>';
704d3260 321 }
549be786 322 $display[] = $val['label'];
704d3260
CW
323 }
324
86bfa4f6 325 $el['html'] = implode('; ', $display) . '<input type="hidden" value="' . $field->getValue() . '" name="' . $field->getAttribute('name') . '">';
704d3260 326 }
5fafc9b0 327
06508628
CW
328 /**
329 * Pre-fill contact name for a custom field of type ContactReference
330 *
331 * Todo: Migrate contact reference fields to use EntityRef
332 *
3c7fd868 333 * @param HTML_QuickForm_element $field
06508628 334 */
00be9182 335 public static function preprocessContactReference($field) {
06508628 336 $val = $field->getValue();
a61d2ab7
CW
337 $multiple = $field->getAttribute('multiple');
338 $data = [];
339 if ($val) {
06508628
CW
340
341 $list = array_keys(CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
342 'contact_reference_options'
343 ), '1');
344
be2fb01f 345 $return = array_unique(array_merge(['sort_name'], $list));
06508628 346
a61d2ab7 347 $cids = is_array($val) ? $val : explode(',', $val);
06508628 348
a61d2ab7
CW
349 foreach ($cids as $cid) {
350 $contact = civicrm_api('contact', 'getsingle', ['id' => $cid, 'return' => $return, 'version' => 3]);
351 if (!empty($contact['id'])) {
352 $view = [];
353 foreach ($return as $fld) {
354 if (!empty($contact[$fld])) {
355 $view[] = $contact[$fld];
356 }
06508628 357 }
a61d2ab7
CW
358 $data[] = [
359 'id' => $contact['id'],
360 'text' => implode(' :: ', $view),
361 ];
06508628 362 }
06508628
CW
363 }
364 }
a61d2ab7
CW
365
366 if ($data) {
367 $field->setAttribute('data-entity-value', json_encode($multiple ? $data : $data[0]));
368 $field->setValue(implode(',', $cids));
369 }
06508628
CW
370 }
371
5fafc9b0
CW
372 /**
373 * @param array $el
374 * @param HTML_QuickForm_element $field
375 */
00be9182 376 public function addOptionsEditLink(&$el, $field) {
5fafc9b0 377 if (CRM_Core_Permission::check('administer CiviCRM')) {
87831073
CW
378 // NOTE: $path is used on the client-side to know which option lists need rebuilding,
379 // that's why we need that bit of data both in the link and in the form element
380 $path = $field->getAttribute('data-option-edit-path');
381 // NOTE: If we ever needed to support arguments in this link other than reset=1 we could split $path here if it contains a ?
382 $url = CRM_Utils_System::url($path, 'reset=1');
2a087bda 383 $icon = CRM_Core_Page::crmIcon('fa-wrench', ts('Edit %1 Options', [1 => $field->getLabel() ?: ts('Field')]));
9c5fbe31
AH
384 $el['html'] .= <<<HEREDOC
385 <a href="$url" class="crm-option-edit-link medium-popup crm-hover-button" target="_blank" data-option-edit-path="$path">$icon</a>
386HEREDOC;
5fafc9b0
CW
387 }
388 }
4a143c04
CW
389
390 /**
391 * @param array $el
392 * @param HTML_QuickForm_element $field
393 */
00be9182 394 public function appendUnselectButton(&$el, $field) {
4a143c04
CW
395 // Initially hide if not needed
396 // Note: visibility:hidden prevents layout jumping around unlike display:none
8a4f27dc 397 $display = $field->getValue() !== NULL ? '' : ' style="visibility:hidden;"';
13a3d214 398 $el['html'] .= ' <a href="#" class="crm-hover-button crm-clear-link"' . $display . ' title="' . ts('Clear') . '"><i class="crm-i fa-times" aria-hidden="true"></i></a>';
4a143c04 399 }
96025800 400
6a488035 401}