bslinkedsetfieldrenderer.class.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 BsSelectObjectFieldRenderer
  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. $oOutput->AddHtml('<div class="form-group ' . $sFieldMandatoryClass . '">');
  56. if ($this->oField->GetLabel() !== '')
  57. {
  58. $oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label">')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
  59. }
  60. $oOutput->AddHtml('<div class="help-block"></div>');
  61. // Rendering table
  62. // - Vars
  63. $sTableId = 'table_' . $this->oField->GetGlobalId();
  64. // - Output
  65. $oOutput->AddHtml(
  66. <<<EOF
  67. <div class="form_linkedset_wrapper">
  68. <div class="row">
  69. <div class="col-xs-12">
  70. <input type="hidden" id="{$this->oField->GetGlobalId()}" name="{$this->oField->GetId()}" value="{$sItemIdsAsJson}" />
  71. <table id="{$sTableId}" data-field-id="{$this->oField->GetId()}" class="table table-striped table-bordered responsive" cellspacing="0" width="100%">
  72. <tbody>
  73. </tbody>
  74. </table>
  75. </div>
  76. </div>
  77. EOF
  78. );
  79. // Rendering table widget
  80. // - Vars
  81. $sEmptyTableLabel = htmlentities(Dict::S('UI:Message:EmptyList:UseAdd'), ENT_QUOTES, 'UTF-8');
  82. $sSelectionOptionHtml = ($this->oField->GetReadOnly()) ? 'false' : '{"style": "multi"}';
  83. $sSelectionInputHtml = ($this->oField->GetReadOnly()) ? '' : '<span class="row_input"><input type="checkbox" name="' . $this->oField->GetId() . '" /></span>';
  84. // - Output
  85. $oOutput->AddJs(
  86. <<<EOF
  87. var oColumnProperties_{$this->oField->GetGlobalId()} = {$sAttributesToDisplayAsJson};
  88. var oRawDatas_{$this->oField->GetGlobalId()} = {$sItemsAsJson};
  89. var oTable_{$this->oField->GetGlobalId()};
  90. var oSelectedItems_{$this->oField->GetGlobalId()} = {};
  91. var getColumnsDefinition_{$this->oField->GetGlobalId()} = function()
  92. {
  93. var aColumnsDefinition = [];
  94. var sFirstColumnId = Object.keys(oColumnProperties_{$this->oField->GetGlobalId()})[0];
  95. for(sKey in oColumnProperties_{$this->oField->GetGlobalId()})
  96. {
  97. // Level main column
  98. aColumnsDefinition.push({
  99. "width": "auto",
  100. "searchable": true,
  101. "sortable": true,
  102. "title": oColumnProperties_{$this->oField->GetGlobalId()}[sKey],
  103. "defaultContent": "",
  104. "type": "html",
  105. "data": "attributes."+sKey+".att_code",
  106. "render": function(data, type, row){
  107. var cellElem;
  108. // Preparing the cell data
  109. if(row.attributes[data].url !== undefined)
  110. {
  111. cellElem = $('<a></a>');
  112. cellElem.attr('target', '_blank').attr('href', row.attributes[data].url);
  113. }
  114. else
  115. {
  116. cellElem = $('<span></span>');
  117. }
  118. cellElem.attr('data-object-id', row.id).html('<span>' + row.attributes[data].value + '</span>');
  119. if(data === sFirstColumnId)
  120. {
  121. cellElem.prepend('{$sSelectionInputHtml}');
  122. }
  123. return cellElem.prop('outerHTML');
  124. },
  125. });
  126. }
  127. return aColumnsDefinition;
  128. };
  129. // Note : Those options should be externalized in an library so we can use them on any DataTables for the portal.
  130. // We would just have to override / complete the necessary elements
  131. oTable_{$this->oField->GetGlobalId()} = $('#{$sTableId}').DataTable({
  132. "language": {
  133. "emptyTable": "{$sEmptyTableLabel}"
  134. },
  135. "displayLength": -1,
  136. "scrollY": "300px",
  137. "scrollCollapse": true,
  138. "dom": 't',
  139. "columns": getColumnsDefinition_{$this->oField->GetGlobalId()}(),
  140. "select": {$sSelectionOptionHtml},
  141. "rowId": "id",
  142. "data": oRawDatas_{$this->oField->GetGlobalId()},
  143. });
  144. EOF
  145. );
  146. // Attaching JS widget
  147. $sObjectInformationsUrl = $this->oField->GetInformationEndpoint();
  148. $oOutput->AddJs(
  149. <<<EOF
  150. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
  151. 'validators': {$this->GetValidatorsAsJson()},
  152. 'get_current_value_callback': function(me, oEvent, oData){
  153. var value = null;
  154. value = JSON.parse(me.element.find('#{$this->oField->GetGlobalId()}').val());
  155. return value;
  156. },
  157. 'set_current_value_callback': function(me, oEvent, oData){
  158. // When we have data (meaning that we picked objects from search)
  159. if(oData !== undefined && Object.keys(oData.values).length > 0)
  160. {
  161. // Retrieving new rows ids
  162. var aObjectIds = Object.keys(oData.values);
  163. // Retrieving rows informations so we can add them
  164. $.post(
  165. '{$sObjectInformationsUrl}',
  166. {
  167. sObjectClass: '{$this->oField->GetTargetClass()}',
  168. aObjectIds: aObjectIds,
  169. aObjectAttCodes: $sAttCodesToDisplayAsJson
  170. },
  171. function(oData){
  172. // Updating datatables
  173. if(oData.items !== undefined)
  174. {
  175. for(var i in oData.items)
  176. {
  177. // Adding item to table only if it's not already there
  178. if($('#{$sTableId} tr#' + oData.items[i].id + '[role="row"]').length === 0)
  179. {
  180. // Making id negative in order to recognize it when persisting
  181. oData.items[i].id = -1 * parseInt(oData.items[i].id);
  182. oTable_{$this->oField->GetGlobalId()}.row.add(oData.items[i]);
  183. }
  184. }
  185. oTable_{$this->oField->GetGlobalId()}.draw();
  186. }
  187. }
  188. )
  189. .done(function(oData){
  190. // Updating hidden field
  191. var aData = oTable_{$this->oField->GetGlobalId()}.rows().data().toArray();
  192. var aObjectIds = [];
  193. for(var i in aData)
  194. {
  195. aObjectIds.push({id: aData[i].id});
  196. }
  197. $('#{$this->oField->GetGlobalId()}').val(JSON.stringify(aObjectIds));
  198. });
  199. }
  200. // We come from a button
  201. else
  202. {
  203. // Updating hidden field
  204. var aData = oTable_{$this->oField->GetGlobalId()}.rows().data().toArray();
  205. var aObjectIds = [];
  206. for(var i in aData)
  207. {
  208. aObjectIds.push({id: aData[i].id});
  209. }
  210. $('#{$this->oField->GetGlobalId()}').val(JSON.stringify(aObjectIds));
  211. }
  212. }
  213. });
  214. EOF
  215. );
  216. // Additional features if in edition mode
  217. if (!$this->oField->GetReadOnly())
  218. {
  219. // Rendering table
  220. // - Vars
  221. $sButtonAllId = 'btn_all_' . $this->oField->GetGlobalId();
  222. $sButtonNoneId = 'btn_none_' . $this->oField->GetGlobalId();
  223. $sButtonRemoveId = 'btn_remove_' . $this->oField->GetGlobalId();
  224. $sButtonAddId = 'btn_add_' . $this->oField->GetGlobalId();
  225. $sLabelAll = Dict::S('Core:BulkExport:CheckAll');
  226. $sLabelNone = Dict::S('Core:BulkExport:UncheckAll');
  227. $sLabelRemove = Dict::S('UI:Button:Remove');
  228. $sLabelAdd = Dict::S('UI:Button:AddObject');
  229. // - Output
  230. $oOutput->AddHtml(
  231. <<<EOF
  232. <div class="row">
  233. <div class="col-xs-6">
  234. <button type="button" class="btn btn-secondary" id="{$sButtonAllId}">{$sLabelAll}</button>
  235. <button type="button" class="btn btn-secondary" id="{$sButtonNoneId}">{$sLabelNone}</button>
  236. </div>
  237. <div class="col-xs-6 text-right">
  238. <button type="button" class="btn btn-danger" id="{$sButtonRemoveId}">{$sLabelRemove}</button>
  239. <button type="button" class="btn btn-default" id="{$sButtonAddId}">{$sLabelAdd}</button>
  240. </div>
  241. </div>
  242. EOF
  243. );
  244. // Rendering table widget
  245. // - Vars
  246. $sAddButtonEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
  247. // - Output
  248. $oOutput->AddJs(
  249. <<<EOF
  250. // Handles items selection/deselection
  251. // - Directly on the table
  252. oTable_{$this->oField->GetGlobalId()}.off('select').on('select', function(oEvent, dt, type, indexes){
  253. var aData = oTable_{$this->oField->GetGlobalId()}.rows(indexes).data().toArray();
  254. // Checking input
  255. $('#{$sTableId} tr[role="row"].selected td:first-child input').prop('checked', true);
  256. // Saving values in temp array
  257. for(var i in aData)
  258. {
  259. var iItemId = aData[i].id;
  260. if(!(iItemId in oSelectedItems_{$this->oField->GetGlobalId()}))
  261. {
  262. oSelectedItems_{$this->oField->GetGlobalId()}[iItemId] = aData[i].name;
  263. }
  264. }
  265. });
  266. oTable_{$this->oField->GetGlobalId()}.off('deselect').on('deselect', function(oEvent, dt, type, indexes){
  267. var aData = oTable_{$this->oField->GetGlobalId()}.rows(indexes).data().toArray();
  268. // Checking input
  269. $('#{$sTableId} tr[role="row"]:not(.selected) td:first-child input').prop('checked', false);
  270. // Saving values in temp array
  271. for(var i in aData)
  272. {
  273. var iItemId = aData[i].id;
  274. if(iItemId in oSelectedItems_{$this->oField->GetGlobalId()})
  275. {
  276. delete oSelectedItems_{$this->oField->GetGlobalId()}[iItemId];
  277. }
  278. }
  279. });
  280. // - From the bottom buttons
  281. $('#{$sButtonAllId}').off('click').on('click', function(){
  282. oTable_{$this->oField->GetGlobalId()}.rows().select();
  283. });
  284. $('#{$sButtonNoneId}').off('click').on('click', function(){
  285. oTable_{$this->oField->GetGlobalId()}.rows().deselect();
  286. });
  287. // Handles items remove/add
  288. $('#{$sButtonRemoveId}').off('click').on('click', function(){
  289. oTable_{$this->oField->GetGlobalId()}.rows({selected: true}).remove().draw();
  290. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").triggerHandler('set_current_value');
  291. });
  292. $('#{$sButtonAddId}').off('click').on('click', function(){
  293. // Creating a new modal
  294. var oModalElem;
  295. if($('.modal[data-source-element="{$sButtonAddId}"]').length === 0)
  296. {
  297. oModalElem = $('#modal-for-all').clone();
  298. oModalElem.attr('id', '').attr('data-source-element', '{$sButtonAddId}').appendTo('body');
  299. }
  300. else
  301. {
  302. oModalElem = $('.modal[data-source-element="{$sButtonAddId}"]').first();
  303. }
  304. // Resizing to small modal
  305. oModalElem.find('.modal-dialog').removeClass('modal-sm').addClass('modal-lg');
  306. // Loading content
  307. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  308. oModalElem.find('.modal-content').load(
  309. '{$sAddButtonEndpoint}',
  310. {
  311. sFormPath: '{$this->oField->GetFormPath()}',
  312. sFieldId: '{$this->oField->GetId()}'
  313. }
  314. );
  315. oModalElem.modal('show');
  316. });
  317. EOF
  318. );
  319. }
  320. }
  321. // ... and in hidden mode
  322. else
  323. {
  324. $oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $sItemIdsAsJson . '" />');
  325. }
  326. // End of table rendering
  327. $oOutput->AddHtml('</div>');
  328. $oOutput->AddHtml('</div>');
  329. return $oOutput;
  330. }
  331. protected function PrepareItems(&$aItems, &$aItemIds)
  332. {
  333. $oValueSet = $this->oField->GetCurrentValue();
  334. $oValueSet->OptimizeColumnLoad(array($this->oField->GetTargetClass() => $this->oField->GetAttributesToDisplay(true)));
  335. while ($oItem = $oValueSet->Fetch())
  336. {
  337. $aItemProperties = array(
  338. 'id' => $oItem->GetKey(),
  339. 'name' => $oItem->GetName(),
  340. 'attributes' => array()
  341. );
  342. // In case of indirect linked set, we must retrieve the remote object
  343. if ($this->oField->IsIndirect())
  344. {
  345. $oRemoteItem = MetaModel::GetObject($this->oField->GetTargetClass(), $oItem->Get($this->oField->GetExtKeyToRemote()));
  346. }
  347. else
  348. {
  349. $oRemoteItem = $oItem;
  350. }
  351. foreach ($this->oField->GetAttributesToDisplay(true) as $sAttCode)
  352. {
  353. if ($sAttCode !== 'id')
  354. {
  355. $aAttProperties = array(
  356. 'att_code' => $sAttCode
  357. );
  358. $oAttDef = MetaModel::GetAttributeDef($this->oField->GetTargetClass(), $sAttCode);
  359. if ($oAttDef->IsExternalKey())
  360. {
  361. $aAttProperties['value'] = $oRemoteItem->Get($sAttCode . '_friendlyname');
  362. }
  363. else
  364. {
  365. $aAttProperties['value'] = $oAttDef->GetValueLabel($oRemoteItem->Get($sAttCode));
  366. }
  367. $aItemProperties['attributes'][$sAttCode] = $aAttProperties;
  368. }
  369. }
  370. $aItems[] = $aItemProperties;
  371. $aItemIds[] = array('id' => $oItem->GetKey());
  372. }
  373. }
  374. /**
  375. * Renders an regular search button
  376. *
  377. * @param RenderingOutput $oOutput
  378. */
  379. protected function RenderRegularSearch(RenderingOutput &$oOutput)
  380. {
  381. $sSearchButtonId = 's_rg_' . $this->oField->GetGlobalId();
  382. $sEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
  383. $oOutput->AddHtml('<div class="col-xs-2 col-lg-1">');
  384. $oOutput->AddHtml('<button type="button" class="btn btn-default" id="' . $sSearchButtonId . '">S</button>');
  385. $oOutput->AddHtml('</div>');
  386. $oOutput->AddJs(
  387. <<<EOF
  388. $('#{$sSearchButtonId}').off('click').on('click', function(){
  389. // Creating a new modal
  390. var oModalElem;
  391. if($('.modal[data-source-element="{$sSearchButtonId}"]').length === 0)
  392. {
  393. oModalElem = $('#modal-for-all').clone();
  394. oModalElem.attr('id', '').attr('data-source-element', '{$sSearchButtonId}').appendTo('body');
  395. }
  396. else
  397. {
  398. oModalElem = $('.modal[data-source-element="{$sSearchButtonId}"]').first();
  399. }
  400. // Resizing to small modal
  401. oModalElem.find('.modal-dialog').removeClass('modal-sm').addClass('modal-lg');
  402. // Loading content
  403. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  404. oModalElem.find('.modal-content').load(
  405. '{$sEndpoint}',
  406. {
  407. sFormPath: '{$this->oField->GetFormPath()}',
  408. sFieldId: '{$this->oField->GetId()}'
  409. }
  410. );
  411. oModalElem.modal('show');
  412. });
  413. EOF
  414. );
  415. }
  416. }