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