bslinkedsetfieldrenderer.class.inc.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. namespace Combodo\iTop\Renderer\Bootstrap\FieldRenderer;
  19. use \utils;
  20. use \Dict;
  21. use \UserRights;
  22. use \InlineImage;
  23. use \DBObjectSet;
  24. use \MetaModel;
  25. use \Combodo\iTop\Renderer\FieldRenderer;
  26. use \Combodo\iTop\Renderer\RenderingOutput;
  27. use \Combodo\iTop\Form\Field\LinkedSetField;
  28. /**
  29. * Description of BsLinkedSetFieldRenderer
  30. *
  31. * @author Guillaume Lajarige <guillaume.lajarige@combodo.com>
  32. */
  33. class BsLinkedSetFieldRenderer extends FieldRenderer
  34. {
  35. /**
  36. * Returns a RenderingOutput for the FieldRenderer's Field
  37. *
  38. * @return \Combodo\iTop\Renderer\RenderingOutput
  39. */
  40. public function Render()
  41. {
  42. $oOutput = new RenderingOutput();
  43. $sFieldMandatoryClass = ($this->oField->GetMandatory()) ? 'form_mandatory' : '';
  44. // Vars to build the table
  45. $sAttributesToDisplayAsJson = json_encode($this->oField->GetAttributesToDisplay());
  46. $sAttCodesToDisplayAsJson = json_encode($this->oField->GetAttributesToDisplay(true));
  47. $aItems = array();
  48. $aItemIds = array();
  49. $this->PrepareItems($aItems, $aItemIds);
  50. $sItemsAsJson = json_encode($aItems);
  51. $sItemIdsAsJson = htmlentities(json_encode($aItemIds), ENT_QUOTES, 'UTF-8');
  52. if (!$this->oField->GetHidden())
  53. {
  54. // Rendering field
  55. $sIsEditable = ($this->oField->GetReadOnly()) ? 'false' : 'true';
  56. $sCollapseTogglerVisibleClass = 'glyphicon-menu-down';
  57. $sCollapseTogglerHiddenClass = 'glyphicon-menu-down collapsed';
  58. $sCollapseTogglerId = 'form_linkedset_toggler_' . $this->oField->GetGlobalId();
  59. $sFieldWrapperId = 'form_linkedset_wrapper_' . $this->oField->GetGlobalId();
  60. $oOutput->AddHtml('<div class="form-group ' . $sFieldMandatoryClass . '">');
  61. if ($this->oField->GetLabel() !== '')
  62. {
  63. $oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label">')
  64. ->AddHtml($this->oField->GetLabel(), true)
  65. ->AddHtml('<a id="' . $sCollapseTogglerId . '" class="form_linkedset_toggler" data-toggle="collapse" href="#' . $sFieldWrapperId . '" aria-expanded="false" aria-controls="' . $sFieldWrapperId . '">')
  66. ->AddHtml('<span class="text">' . count($aItemIds) . '</span>')
  67. ->AddHtml('<span class="glyphicon ' . $sCollapseTogglerHiddenClass . '"></>')
  68. ->AddHtml('</a>')
  69. ->AddHtml('</label>');
  70. }
  71. $oOutput->AddHtml('<div class="help-block"></div>');
  72. // Rendering table
  73. // - Vars
  74. $sTableId = 'table_' . $this->oField->GetGlobalId();
  75. // - Output
  76. $oOutput->AddHtml(
  77. <<<EOF
  78. <div class="form_linkedset_wrapper collapse" id="{$sFieldWrapperId}">
  79. <div class="row">
  80. <div class="col-xs-12">
  81. <input type="hidden" id="{$this->oField->GetGlobalId()}" name="{$this->oField->GetId()}" value="{$sItemIdsAsJson}" />
  82. <table id="{$sTableId}" data-field-id="{$this->oField->GetId()}" class="table table-striped table-bordered responsive" cellspacing="0" width="100%">
  83. <tbody>
  84. </tbody>
  85. </table>
  86. </div>
  87. </div>
  88. EOF
  89. );
  90. // Rendering table widget
  91. // - Vars
  92. $sEmptyTableLabel = htmlentities(Dict::S(($this->oField->GetReadOnly()) ? 'Portal:Datatables:Language:EmptyTable' : 'UI:Message:EmptyList:UseAdd'), ENT_QUOTES, 'UTF-8');
  93. $sLabelGeneralCheckbox = htmlentities(Dict::S('Core:BulkExport:CheckAll') . ' / ' . Dict::S('Core:BulkExport:UncheckAll'), ENT_QUOTES, 'UTF-8');
  94. $sSelectionOptionHtml = ($this->oField->GetReadOnly()) ? 'false' : '{"style": "multi"}';
  95. $sSelectionInputGlobalHtml = ($this->oField->GetReadOnly()) ? '' : '<span class="row_input"><input type="checkbox" id="' . $this->oField->GetGlobalId() . '_check_all" name="' . $this->oField->GetGlobalId() . '_check_all" title="' . $sLabelGeneralCheckbox . '" /></span>';
  96. $sSelectionInputHtml = ($this->oField->GetReadOnly()) ? '' : '<span class="row_input"><input type="checkbox" name="' . $this->oField->GetGlobalId() . '" /></span>';
  97. // - Output
  98. $oOutput->AddJs(
  99. <<<EOF
  100. // Collapse handlers
  101. // - Collapsing by default to optimize form space
  102. // It would be better to be able to construct the widget as collapsed, but in this ase, datatables thinks the container is very small and therefore renders the table as if it was in microbox.
  103. $('#{$sFieldWrapperId}').collapse({toggle: false});
  104. // - Change toggle icon class
  105. $('#{$sFieldWrapperId}').on('shown.bs.collapse', function(){
  106. // Creating the table if null (first expand). If we create it on start, it will be displayed as if it was in a micro screen due to the div being "display: none;"
  107. if(oTable_{$this->oField->GetGlobalId()} === undefined)
  108. {
  109. buildTable_{$this->oField->GetGlobalId()}();
  110. }
  111. })
  112. .on('show.bs.collapse', function(){
  113. $('#{$sCollapseTogglerId} > span.glyphicon').removeClass('{$sCollapseTogglerHiddenClass}').addClass('{$sCollapseTogglerVisibleClass}');
  114. })
  115. .on('hide.bs.collapse', function(){
  116. $('#{$sCollapseTogglerId} > span.glyphicon').removeClass('{$sCollapseTogglerVisibleClass}').addClass('{$sCollapseTogglerHiddenClass}');
  117. });
  118. // Places a loader in the empty datatables
  119. $('#{$sTableId} > tbody').html('<tr><td class="datatables_overlay" colspan="100">' + $('#page_overlay').html() + '</td></tr>');
  120. // Prepares data for datatables
  121. var oColumnProperties_{$this->oField->GetGlobalId()} = {$sAttributesToDisplayAsJson};
  122. var oRawDatas_{$this->oField->GetGlobalId()} = {$sItemsAsJson};
  123. var oTable_{$this->oField->GetGlobalId()};
  124. var oSelectedItems_{$this->oField->GetGlobalId()} = {};
  125. var getColumnsDefinition_{$this->oField->GetGlobalId()} = function()
  126. {
  127. var aColumnsDefinition = [];
  128. if({$sIsEditable})
  129. {
  130. aColumnsDefinition.push({
  131. "width": "auto",
  132. "searchable": false,
  133. "sortable": false,
  134. "title": '{$sSelectionInputGlobalHtml}',
  135. "type": "html",
  136. "data": "",
  137. "render": function(data, type, row){ return '{$sSelectionInputHtml}'; }
  138. });
  139. }
  140. for(sKey in oColumnProperties_{$this->oField->GetGlobalId()})
  141. {
  142. // Level main column
  143. aColumnsDefinition.push({
  144. "width": "auto",
  145. "searchable": true,
  146. "sortable": true,
  147. "title": oColumnProperties_{$this->oField->GetGlobalId()}[sKey],
  148. "defaultContent": "",
  149. "type": "html",
  150. "data": "attributes."+sKey+".att_code",
  151. "render": function(data, type, row){
  152. var cellElem;
  153. // Preparing the cell data
  154. if(row.attributes[data].url !== undefined)
  155. {
  156. cellElem = $('<a></a>');
  157. cellElem.attr('target', '_blank').attr('href', row.attributes[data].url);
  158. }
  159. else
  160. {
  161. cellElem = $('<span></span>');
  162. }
  163. cellElem.attr('data-object-id', row.id).html('<span>' + row.attributes[data].value + '</span>');
  164. return cellElem.prop('outerHTML');
  165. },
  166. });
  167. }
  168. return aColumnsDefinition;
  169. };
  170. // Helper to build the datatable
  171. // Note : Those options should be externalized in an library so we can use them on any DataTables for the portal.
  172. // We would just have to override / complete the necessary elements
  173. var buildTable_{$this->oField->GetGlobalId()} = function()
  174. {
  175. var iDefaultOrderColumnIndex = ({$sIsEditable}) ? 1 : 0;
  176. // Instanciates datatables
  177. oTable_{$this->oField->GetGlobalId()} = $('#{$sTableId}').DataTable({
  178. "language": {
  179. "emptyTable": "{$sEmptyTableLabel}"
  180. },
  181. "displayLength": -1,
  182. "scrollY": "300px",
  183. "scrollCollapse": true,
  184. "order": [[iDefaultOrderColumnIndex, "asc"]],
  185. "dom": 't',
  186. "columns": getColumnsDefinition_{$this->oField->GetGlobalId()}(),
  187. "select": {$sSelectionOptionHtml},
  188. "rowId": "id",
  189. "data": oRawDatas_{$this->oField->GetGlobalId()},
  190. });
  191. // Handles items selection/deselection
  192. // - Directly on the table
  193. oTable_{$this->oField->GetGlobalId()}.off('select').on('select', function(oEvent, dt, type, indexes){
  194. var aData = oTable_{$this->oField->GetGlobalId()}.rows(indexes).data().toArray();
  195. // Checking input
  196. $('#{$sTableId} tbody tr[role="row"].selected td:first-child input').prop('checked', true);
  197. // Saving values in temp array
  198. for(var i in aData)
  199. {
  200. var iItemId = aData[i].id;
  201. if(!(iItemId in oSelectedItems_{$this->oField->GetGlobalId()}))
  202. {
  203. oSelectedItems_{$this->oField->GetGlobalId()}[iItemId] = aData[i].name;
  204. }
  205. }
  206. // Updating remove button
  207. updateRemoveButtonState_{$this->oField->GetGlobalId()}();
  208. });
  209. oTable_{$this->oField->GetGlobalId()}.off('deselect').on('deselect', function(oEvent, dt, type, indexes){
  210. var aData = oTable_{$this->oField->GetGlobalId()}.rows(indexes).data().toArray();
  211. // Checking input
  212. $('#{$sTableId} tbody tr[role="row"]:not(.selected) td:first-child input').prop('checked', false);
  213. // Saving values in temp array
  214. for(var i in aData)
  215. {
  216. var iItemId = aData[i].id;
  217. if(iItemId in oSelectedItems_{$this->oField->GetGlobalId()})
  218. {
  219. delete oSelectedItems_{$this->oField->GetGlobalId()}[iItemId];
  220. }
  221. }
  222. // Unchecking global checkbox
  223. $('#{$this->oField->GetGlobalId()}_check_all').prop('checked', false);
  224. // Updating remove button
  225. updateRemoveButtonState_{$this->oField->GetGlobalId()}();
  226. });
  227. // - From the global button
  228. $('#{$this->oField->GetGlobalId()}_check_all').off('click').on('click', function(oEvent){
  229. if($(this).prop('checked'))
  230. {
  231. oTable_{$this->oField->GetGlobalId()}.rows().select();
  232. }
  233. else
  234. {
  235. oTable_{$this->oField->GetGlobalId()}.rows().deselect();
  236. }
  237. updateRemoveButtonState_{$this->oField->GetGlobalId()}();
  238. });
  239. };
  240. EOF
  241. );
  242. // Attaching JS widget
  243. $sObjectInformationsUrl = $this->oField->GetInformationEndpoint();
  244. $oOutput->AddJs(
  245. <<<EOF
  246. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
  247. 'validators': {$this->GetValidatorsAsJson()},
  248. 'get_current_value_callback': function(me, oEvent, oData){
  249. var value = null;
  250. // Retrieving JSON value as a string and not an object
  251. //
  252. // Note : The value is passed as a string instead of an array because the attribute would not be included in the posted data when empty.
  253. // Which was an issue when deleting all objects from linkedset
  254. //
  255. // Old code : value = JSON.parse(me.element.find('#{$this->oField->GetGlobalId()}').val());
  256. value = me.element.find('#{$this->oField->GetGlobalId()}').val();
  257. return value;
  258. },
  259. 'set_current_value_callback': function(me, oEvent, oData){
  260. // When we have data (meaning that we picked objects from search)
  261. if(oData !== undefined && Object.keys(oData.values).length > 0)
  262. {
  263. // Showing loader while retrieving informations
  264. $('#page_overlay').fadeIn(200);
  265. // Retrieving new rows ids
  266. var aObjectIds = Object.keys(oData.values);
  267. // Retrieving rows informations so we can add them
  268. $.post(
  269. '{$sObjectInformationsUrl}',
  270. {
  271. sObjectClass: '{$this->oField->GetTargetClass()}',
  272. aObjectIds: aObjectIds,
  273. aObjectAttCodes: $sAttCodesToDisplayAsJson
  274. },
  275. function(oData){
  276. // Updating datatables
  277. if(oData.items !== undefined)
  278. {
  279. for(var i in oData.items)
  280. {
  281. // Adding item to table only if it's not already there
  282. if($('#{$sTableId} tr#' + oData.items[i].id + '[role="row"]').length === 0)
  283. {
  284. // Making id negative in order to recognize it when persisting
  285. oData.items[i].id = -1 * parseInt(oData.items[i].id);
  286. oTable_{$this->oField->GetGlobalId()}.row.add(oData.items[i]);
  287. }
  288. }
  289. oTable_{$this->oField->GetGlobalId()}.draw();
  290. }
  291. }
  292. )
  293. .done(function(oData){
  294. // Updating hidden field
  295. var aData = oTable_{$this->oField->GetGlobalId()}.rows().data().toArray();
  296. var aObjectIds = [];
  297. for(var i in aData)
  298. {
  299. aObjectIds.push({id: aData[i].id});
  300. }
  301. $('#{$this->oField->GetGlobalId()}').val(JSON.stringify(aObjectIds));
  302. // Updating items count
  303. updateItemCount();
  304. // Updating global checkbox
  305. $('#{$this->oField->GetGlobalId()}_check_all').prop('checked', false);
  306. })
  307. .always(function(oData){
  308. // Hiding loader
  309. $('#page_overlay').fadeOut(200);
  310. });
  311. }
  312. // We come from a button
  313. else
  314. {
  315. // Updating hidden field
  316. var aData = oTable_{$this->oField->GetGlobalId()}.rows().data().toArray();
  317. var aObjectIds = [];
  318. for(var i in aData)
  319. {
  320. aObjectIds.push({id: aData[i].id});
  321. }
  322. $('#{$this->oField->GetGlobalId()}').val(JSON.stringify(aObjectIds));
  323. // Updating items count
  324. updateItemCount();
  325. // Updating global checkbox
  326. $('#{$this->oField->GetGlobalId()}_check_all').prop('checked', false);
  327. }
  328. }
  329. });
  330. EOF
  331. );
  332. // Additional features if in edition mode
  333. if (!$this->oField->GetReadOnly())
  334. {
  335. // Rendering table
  336. // - Vars
  337. $sButtonRemoveId = 'btn_remove_' . $this->oField->GetGlobalId();
  338. $sButtonAddId = 'btn_add_' . $this->oField->GetGlobalId();
  339. $sLabelRemove = Dict::S('UI:Button:Remove');
  340. $sLabelAdd = Dict::S('UI:Button:AddObject');
  341. // - Output
  342. $oOutput->AddHtml(
  343. <<<EOF
  344. <div class="row">
  345. <div class="col-xs-12">
  346. <div class="btn-group" role="group">
  347. <button type="button" class="btn btn-sm btn-danger" id="{$sButtonRemoveId}" title="{$sLabelRemove}" disabled><span class="glyphicon glyphicon-minus"></span></button>
  348. <button type="button" class="btn btn-sm btn-default" id="{$sButtonAddId}" title="{$sLabelAdd}"><span class="glyphicon glyphicon-plus"></span></button>
  349. </div>
  350. </div>
  351. </div>
  352. EOF
  353. );
  354. // Rendering table widget
  355. // - Vars
  356. $sAddButtonEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
  357. // - Output
  358. $oOutput->AddJs(
  359. <<<EOF
  360. // Handles items selection/deselection
  361. // - Remove button state handler
  362. var updateRemoveButtonState_{$this->oField->GetGlobalId()} = function()
  363. {
  364. var bIsDisabled = (Object.keys(oSelectedItems_{$this->oField->GetGlobalId()}).length == 0);
  365. $('#{$sButtonRemoveId}').prop('disabled', bIsDisabled);
  366. };
  367. // - Item count state handler
  368. var updateItemCount = function()
  369. {
  370. console.log(oSelectedItems_{$this->oField->GetGlobalId()});
  371. $('#{$sCollapseTogglerId} > .text').text( oTable_{$this->oField->GetGlobalId()}.rows().count() );
  372. };
  373. // Handles items remove/add
  374. $('#{$sButtonRemoveId}').off('click').on('click', function(){
  375. // Removing items from table
  376. oTable_{$this->oField->GetGlobalId()}.rows({selected: true}).remove().draw();
  377. // Resetting selected items
  378. oSelectedItems_{$this->oField->GetGlobalId()} = {};
  379. // Updating form value
  380. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").triggerHandler('set_current_value');
  381. // Updating global checkbox state
  382. $('#{$this->oField->GetGlobalId()}_check_all').prop('checked', false);
  383. // Updating remove button
  384. updateRemoveButtonState_{$this->oField->GetGlobalId()}();
  385. });
  386. $('#{$sButtonAddId}').off('click').on('click', function(){
  387. // Preparing current values
  388. var aFieldValue = JSON.parse( $('#{$this->oField->GetGlobalId()}').val() );
  389. var aObjectIdsToIgnore = [];
  390. for(var i in aFieldValue)
  391. {
  392. aObjectIdsToIgnore.push( Math.abs(aFieldValue[i].id) );
  393. }
  394. // Creating a new modal
  395. var oModalElem;
  396. if($('.modal[data-source-element="{$sButtonAddId}"]').length === 0)
  397. {
  398. oModalElem = $('#modal-for-all').clone();
  399. oModalElem.attr('id', '').attr('data-source-element', '{$sButtonAddId}').appendTo('body');
  400. }
  401. else
  402. {
  403. oModalElem = $('.modal[data-source-element="{$sButtonAddId}"]').first();
  404. }
  405. // Resizing to small modal
  406. oModalElem.find('.modal-dialog').removeClass('modal-sm').addClass('modal-lg');
  407. // Loading content
  408. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  409. oModalElem.find('.modal-content').load(
  410. '{$sAddButtonEndpoint}',
  411. {
  412. sFormPath: '{$this->oField->GetFormPath()}',
  413. sFieldId: '{$this->oField->GetId()}',
  414. aObjectIdsToIgnore : aObjectIdsToIgnore
  415. }
  416. );
  417. oModalElem.modal('show');
  418. });
  419. EOF
  420. );
  421. }
  422. }
  423. // ... and in hidden mode
  424. else
  425. {
  426. $oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $sItemIdsAsJson . '" />');
  427. }
  428. // End of table rendering
  429. $oOutput->AddHtml('</div>');
  430. $oOutput->AddHtml('</div>');
  431. return $oOutput;
  432. }
  433. protected function PrepareItems(&$aItems, &$aItemIds)
  434. {
  435. $oValueSet = $this->oField->GetCurrentValue();
  436. $oValueSet->OptimizeColumnLoad(array($this->oField->GetTargetClass() => $this->oField->GetAttributesToDisplay(true)));
  437. while ($oItem = $oValueSet->Fetch())
  438. {
  439. $aItemProperties = array(
  440. 'id' => $oItem->GetKey(),
  441. 'name' => $oItem->GetName(),
  442. 'attributes' => array()
  443. );
  444. // In case of indirect linked set, we must retrieve the remote object
  445. if ($this->oField->IsIndirect())
  446. {
  447. $oRemoteItem = MetaModel::GetObject($this->oField->GetTargetClass(), $oItem->Get($this->oField->GetExtKeyToRemote()));
  448. }
  449. else
  450. {
  451. $oRemoteItem = $oItem;
  452. }
  453. foreach ($this->oField->GetAttributesToDisplay(true) as $sAttCode)
  454. {
  455. if ($sAttCode !== 'id')
  456. {
  457. $aAttProperties = array(
  458. 'att_code' => $sAttCode
  459. );
  460. $oAttDef = MetaModel::GetAttributeDef($this->oField->GetTargetClass(), $sAttCode);
  461. if ($oAttDef->IsExternalKey())
  462. {
  463. $aAttProperties['value'] = $oRemoteItem->Get($sAttCode . '_friendlyname');
  464. }
  465. else
  466. {
  467. $aAttProperties['value'] = $oAttDef->GetValueLabel($oRemoteItem->Get($sAttCode));
  468. }
  469. $aItemProperties['attributes'][$sAttCode] = $aAttProperties;
  470. }
  471. }
  472. $aItems[] = $aItemProperties;
  473. $aItemIds[] = array('id' => $oItem->GetKey());
  474. }
  475. }
  476. }