Merge pull request #10532 from monishdeb/CRM-20488_soft_credit_organization
[civicrm-core.git] / CRM / Core / Form / Renderer.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
32 * $Id$
33 *
34 */
35
36 require_once 'HTML/QuickForm/Renderer/ArraySmarty.php';
37
38 /**
39 * Customize QF output to meet our specific requirements
40 */
41 class 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
48 */
49 static private $_singleton = NULL;
50
51 /**
52 * The converter from array size to css class.
53 *
54 * @var array
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 /**
68 * Constructor.
69 */
70 public function __construct() {
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 */
80 public static function &singleton() {
81 if (!isset(self::$_singleton)) {
82 self::$_singleton = new CRM_Core_Form_Renderer();
83 }
84 return self::$_singleton;
85 }
86
87 /**
88 * Creates an array representing an element containing.
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 *
93 *
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.
99 *
100 * @return array
101 */
102 public function _elementToArray(&$element, $required, $error) {
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
118 // Display-only (frozen) elements
119 if (!empty($el['frozen'])) {
120 if ($element->getAttribute('data-api-entity') && $element->getAttribute('data-entity-value')) {
121 $this->renderFrozenEntityRef($el, $element);
122 }
123 elseif ($element->getAttribute('type') == 'text' && $element->getAttribute('data-select-params')) {
124 $this->renderFrozenSelect2($el, $element);
125 }
126 elseif ($element->getAttribute('type') == 'text' && $element->getAttribute('formatType')) {
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') . '">';
130 }
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>';
134 }
135 else {
136 $el['html'] = '<span class="crm-frozen-field">' . $el['html'] . '</span>';
137 }
138 }
139 // Active form elements
140 else {
141 if ($element->getType() == 'select' && $element->getAttribute('data-option-edit-path')) {
142 $this->addOptionsEditLink($el, $element);
143 }
144
145 if ($element->getAttribute('allowClear')) {
146 $this->appendUnselectButton($el, $element);
147 }
148 }
149
150 return $el;
151 }
152
153 /**
154 * Update the attributes of this element and add a few CiviCRM
155 * based attributes so we can style this form element better
156 *
157 *
158 * @param HTML_QuickForm_element $element
159 * @param bool $required
160 * Whether an element is required.
161 * @param string $error
162 * Error associated with the element.
163 *
164 */
165 public static function updateAttributes(&$element, $required, $error) {
166 // lets create an id for all input elements, so we can generate nice label tags
167 // to make it nice and clean, we'll just use the elementName if it is non null
168 $attributes = array();
169 if (!$element->getAttribute('id')) {
170 $name = $element->getAttribute('name');
171 if ($name) {
172 $attributes['id'] = str_replace(array(']', '['),
173 array('', '_'),
174 $name
175 );
176 }
177 }
178
179 $class = $element->getAttribute('class');
180 $type = $element->getType();
181 if (!$class) {
182 if ($type == 'text') {
183 $size = $element->getAttribute('size');
184 if (!empty($size)) {
185 $class = CRM_Utils_Array::value($size, self::$_sizeMapper);
186 }
187 }
188 }
189
190 if ($type == 'select' && $element->getAttribute('multiple')) {
191 $type = 'multiselect';
192 }
193 // Add widget-specific class
194 if (!$class || strpos($class, 'crm-form-') === FALSE) {
195 $class = ($class ? "$class " : '') . 'crm-form-' . $type;
196 }
197 elseif (strpos($class, 'crm-form-entityref') !== FALSE) {
198 self::preProcessEntityRef($element);
199 }
200 elseif (strpos($class, 'crm-form-contact-reference') !== FALSE) {
201 self::preprocessContactReference($element);
202 }
203 // Hack to support html5 fields (number, url, etc)
204 else {
205 foreach (CRM_Core_Form::$html5Types as $type) {
206 if (strpos($class, "crm-form-$type") !== FALSE) {
207 $element->setAttribute('type', $type);
208 // Also add the "base" class for consistent styling
209 $class .= ' crm-form-text';
210 break;
211 }
212 }
213 }
214
215 if ($required) {
216 $class .= ' required';
217 }
218
219 if ($error) {
220 $class .= ' error';
221 }
222
223 $attributes['class'] = $class;
224 $element->updateAttributes($attributes);
225 }
226
227 /**
228 * Convert IDs to values and format for display.
229 *
230 * @param HTML_QuickForm_element $field
231 */
232 public static function preProcessEntityRef($field) {
233 $val = $field->getValue();
234 // Temporarily convert string values to an array
235 if (!is_array($val)) {
236 // Try to auto-detect method of serialization
237 $val = strpos($val, ',') ? explode(',', str_replace(', ', ',', $val)) : (array) CRM_Utils_Array::explodePadded($val);
238 }
239 if ($val) {
240 $entity = $field->getAttribute('data-api-entity');
241 // Get api params, ensure it is an array
242 $params = $field->getAttribute('data-api-params');
243 $params = $params ? json_decode($params, TRUE) : array();
244 $result = civicrm_api3($entity, 'getlist', array('id' => $val) + $params);
245 if ($field->isFrozen()) {
246 // Prevent js from treating frozen entityRef as a "live" field
247 $field->removeAttribute('class');
248 }
249 if (!empty($result['values'])) {
250 $field->setAttribute('data-entity-value', json_encode($result['values']));
251 }
252 // CRM-15803 - Remove invalid values
253 $val = array_intersect($val, CRM_Utils_Array::collect('id', $result['values']));
254 }
255 // Convert array values back to a string
256 $field->setValue(implode(',', $val));
257 }
258
259 /**
260 * Render select2 as text.
261 *
262 * @param array $el
263 * @param HTML_QuickForm_element $field
264 */
265 public function renderFrozenSelect2(&$el, $field) {
266 $params = json_decode($field->getAttribute('data-select-params'), TRUE);
267 $val = $field->getValue();
268 if ($val && !empty($params['data'])) {
269 $display = array();
270 foreach (explode(',', $val) as $item) {
271 $match = CRM_Utils_Array::findInTree($item, $params['data']);
272 if (isset($match['text']) && strlen($match['text'])) {
273 $display[] = $match['text'];
274 }
275 }
276 $el['html'] = implode('; ', $display) . '<input type="hidden" value="' . $field->getValue() . '" name="' . $field->getAttribute('name') . '">';
277 }
278 }
279
280 /**
281 * Render entity references as text.
282 * If user has permission, format as link (for now limited to contacts).
283 *
284 * @param array $el
285 * @param HTML_QuickForm_element $field
286 */
287 public function renderFrozenEntityRef(&$el, $field) {
288 $entity = strtolower($field->getAttribute('data-api-entity'));
289 $vals = json_decode($field->getAttribute('data-entity-value'), TRUE);
290 $display = array();
291
292 // Custom fields of type contactRef store their data in a slightly different format
293 if ($field->getAttribute('data-crm-custom') && $entity == 'contact') {
294 $vals = array(array('id' => $vals['id'], 'label' => $vals['text']));
295 }
296
297 foreach ($vals as $val) {
298 // Format contact as link
299 if ($entity == 'contact' && CRM_Contact_BAO_Contact_Permission::allow($val['id'], CRM_Core_Permission::VIEW)) {
300 $url = CRM_Utils_System::url("civicrm/contact/view", array('reset' => 1, 'cid' => $val['id']));
301 $val['label'] = '<a class="view-' . $entity . ' no-popup" href="' . $url . '" title="' . ts('View Contact') . '">' . $val['label'] . '</a>';
302 }
303 $display[] = $val['label'];
304 }
305
306 $el['html'] = implode('; ', $display) . '<input type="hidden" value="' . $field->getValue() . '" name="' . $field->getAttribute('name') . '">';
307 }
308
309 /**
310 * Pre-fill contact name for a custom field of type ContactReference
311 *
312 * Todo: Migrate contact reference fields to use EntityRef
313 *
314 * @param HTML_QuickForm_element $field
315 */
316 public static function preprocessContactReference($field) {
317 $val = $field->getValue();
318 if ($val && is_numeric($val)) {
319
320 $list = array_keys(CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
321 'contact_reference_options'
322 ), '1');
323
324 $return = array_unique(array_merge(array('sort_name'), $list));
325
326 $contact = civicrm_api('contact', 'getsingle', array('id' => $val, 'return' => $return, 'version' => 3));
327
328 if (!empty($contact['id'])) {
329 $view = array();
330 foreach ($return as $fld) {
331 if (!empty($contact[$fld])) {
332 $view[] = $contact[$fld];
333 }
334 }
335 $field->setAttribute('data-entity-value', json_encode(array(
336 'id' => $contact['id'],
337 'text' => implode(' :: ', $view),
338 )));
339 }
340 }
341 }
342
343 /**
344 * @param array $el
345 * @param HTML_QuickForm_element $field
346 */
347 public function addOptionsEditLink(&$el, $field) {
348 if (CRM_Core_Permission::check('administer CiviCRM')) {
349 // NOTE: $path is used on the client-side to know which option lists need rebuilding,
350 // that's why we need that bit of data both in the link and in the form element
351 $path = $field->getAttribute('data-option-edit-path');
352 // NOTE: If we ever needed to support arguments in this link other than reset=1 we could split $path here if it contains a ?
353 $url = CRM_Utils_System::url($path, 'reset=1');
354 $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>';
355 }
356 }
357
358 /**
359 * @param array $el
360 * @param HTML_QuickForm_element $field
361 */
362 public function appendUnselectButton(&$el, $field) {
363 // Initially hide if not needed
364 // Note: visibility:hidden prevents layout jumping around unlike display:none
365 $display = $field->getValue() !== NULL ? '' : ' style="visibility:hidden;"';
366 $el['html'] .= ' <a href="#" class="crm-hover-button crm-clear-link"' . $display . ' title="' . ts('Clear') . '"><i class="crm-i fa-times"></i></a>';
367 }
368
369 }