bsselectobjectfieldrenderer.class.inc.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. // Copyright (C) 2010-2017 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 \Exception;
  20. use \CoreException;
  21. use \utils;
  22. use \IssueLog;
  23. use \Dict;
  24. use \UserRights;
  25. use \InlineImage;
  26. use \DBObjectSet;
  27. use \MetaModel;
  28. use \Combodo\iTop\Renderer\FieldRenderer;
  29. use \Combodo\iTop\Renderer\RenderingOutput;
  30. use \Combodo\iTop\Form\Field\SelectObjectField;
  31. /**
  32. * Description of BsSelectObjectFieldRenderer
  33. *
  34. * @author Guillaume Lajarige <guillaume.lajarige@combodo.com>
  35. */
  36. class BsSelectObjectFieldRenderer extends FieldRenderer
  37. {
  38. /**
  39. * Returns a RenderingOutput for the FieldRenderer's Field
  40. *
  41. * @return \Combodo\iTop\Renderer\RenderingOutput
  42. */
  43. public function Render()
  44. {
  45. $oOutput = new RenderingOutput();
  46. $oOutput->AddCssClass('form_field_' . $this->oField->GetDisplayMode());
  47. $sFieldValueClass = $this->oField->GetSearch()->GetClass();
  48. $sFieldMandatoryClass = ($this->oField->GetMandatory()) ? 'form_mandatory' : '';
  49. $iFieldControlType = $this->oField->GetControlType();
  50. // TODO : Remove this when hierarchical search supported
  51. $this->oField->SetHierarchical(false);
  52. // Rendering field in edition mode
  53. if (!$this->oField->GetReadOnly() && !$this->oField->GetHidden())
  54. {
  55. // Rendering field
  56. // - Opening container
  57. $oOutput->AddHtml('<div class="form-group form_group_small ' . $sFieldMandatoryClass . '">');
  58. // Label
  59. $oOutput->AddHtml('<div class="form_field_label">');
  60. if ($this->oField->GetLabel() !== '')
  61. {
  62. $oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label">')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
  63. }
  64. $oOutput->AddHtml('</div>');
  65. // Value
  66. $oOutput->AddHtml('<div class="form_field_control">');
  67. $oOutput->AddHtml('<div class="help-block"></div>');
  68. // - As a select
  69. // TODO : This should be changed when we do the radio button display. For now we display everything with select
  70. //if ($iFieldControlType === SelectObjectField::CONTROL_SELECT)
  71. if (true)
  72. {
  73. // Checking if regular select or autocomplete
  74. $oSearch = $this->oField->GetSearch()->DeepClone();
  75. $oCountSet = new DBObjectSet($oSearch);
  76. $iSetCount = $oCountSet->Count();
  77. // Note : Autocomplete/Search is disabled for template fields as they are not external keys, thus they will just be displayed as regular select.
  78. $bRegularSelect = ( ($iSetCount <= $this->oField->GetMaximumComboLength()) || ($this->oField->GetSearchEndpoint() === null) || ($this->oField->GetSearchEndpoint() === '') );
  79. unset($oCountSet);
  80. // - For regular select
  81. if ($bRegularSelect)
  82. {
  83. // HTML for select part
  84. // - Opening row
  85. $oOutput->AddHtml('<div class="row">');
  86. // - Rendering select
  87. $oOutput->AddHtml('<div class="col-xs-' . ( $this->oField->GetHierarchical() ? 10 : 12 ) . ' col-sm-' . ( $this->oField->GetHierarchical() ? 9 : 12 ) . ' col-md-' . ( $this->oField->GetHierarchical() ? 10 : 12 ) . '">');
  88. $oOutput->AddHtml('<select id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" class="form-control">');
  89. $oOutput->AddHtml('<option value="">')->AddHtml(Dict::S('UI:SelectOne'), false)->AddHtml('</option>');
  90. // - Retrieving choices
  91. $oChoicesSet = new DBObjectSet($oSearch);
  92. while ($oChoice = $oChoicesSet->Fetch())
  93. {
  94. // Note : The test is a double equal on purpose as the type of the value received from the XHR is not always the same as the type of the allowed values. (eg : string vs int)
  95. $sSelectedAtt = ($this->oField->GetCurrentValue() == $oChoice->GetKey()) ? 'selected' : '';
  96. $oOutput->AddHtml('<option value="' . $oChoice->GetKey() . '" ' . $sSelectedAtt . ' >')->AddHtml($oChoice->GetName(), false)->AddHtml('</option>');
  97. }
  98. unset($oChoicesSet);
  99. $oOutput->AddHtml('</select>');
  100. $oOutput->AddHtml('</div>');
  101. // - Closing col for autocomplete & opening col for hierarchy, rendering hierarchy button, closing col and row
  102. $oOutput->AddHtml('<div class="col-xs-' . ( $this->oField->GetHierarchical() ? 2 : 0 ) . ' col-sm-' . ( $this->oField->GetHierarchical() ? 3 : 0 ) . ' col-md-' . ( $this->oField->GetHierarchical() ? 2 : 0 ) . ' text-right">');
  103. $this->RenderHierarchicalSearch($oOutput);
  104. $oOutput->AddHtml('</div>');
  105. // - Closing row
  106. $oOutput->AddHtml('</div>');
  107. // JS FieldChange trigger (:input are not always at the same depth)
  108. $oOutput->AddJs(
  109. <<<EOF
  110. $("#{$this->oField->GetGlobalId()}").off("change keyup").on("change keyup", function(){
  111. var me = this;
  112. $(this).closest(".field_set").trigger("field_change", {
  113. id: $(me).attr("id"),
  114. name: $(me).closest(".form_field").attr("data-field-id"),
  115. value: $(me).val()
  116. });
  117. });
  118. EOF
  119. );
  120. // Attaching JS widget
  121. $oOutput->AddJs(
  122. <<<EOF
  123. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
  124. 'validators': {$this->GetValidatorsAsJson()}
  125. });
  126. EOF
  127. );
  128. }
  129. // - For autocomplete
  130. else
  131. {
  132. $sAutocompleteFieldId = 's_ac_' . $this->oField->GetGlobalId();
  133. $sEndpoint = str_replace('-sMode-', 'autocomplete', $this->oField->GetSearchEndpoint());
  134. $sNoResultText = Dict::S('Portal:Autocomplete:NoResult');
  135. // Retrieving field value
  136. if (($this->oField->GetCurrentValue() !== null) && ($this->oField->GetCurrentValue() !== 0) && ($this->oField->GetCurrentValue() !== ''))
  137. {
  138. try
  139. {
  140. // Note : AllowAllData set to true here instead of checking scope's flag because we are displaying a value that has been set and validated
  141. $oFieldValue = MetaModel::GetObject($sFieldValueClass, $this->oField->GetCurrentValue(), true, true);
  142. }
  143. catch (CoreException $e)
  144. {
  145. IssueLog::Error('Could not retrieve object ' . $sFieldValueClass . '::' . $this->oField->GetCurrentValue() . ' for "' . $this->oField->GetId() . '" field.');
  146. throw new Exception($e->getMessage(), $e->getCode(), $e->getPrevious());
  147. }
  148. $sFieldValue = $oFieldValue->GetName();
  149. }
  150. else
  151. {
  152. $sFieldValue = '';
  153. }
  154. // HTML for autocomplete part
  155. // - Opening input group
  156. $oOutput->AddHtml('<div class="input-group selectobject">');
  157. // - Rendering autocomplete search
  158. $oOutput->AddHtml('<input type="text" id="' . $sAutocompleteFieldId . '" name="' . $sAutocompleteFieldId . '" value="')->AddHtml($sFieldValue)->AddHtml('" data-target-id="' . $this->oField->GetGlobalId() . ' "class="form-control" />');
  159. $oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $this->oField->GetCurrentValue() . '" />');
  160. // - Rendering buttons
  161. // - Rendering hierarchy button
  162. $this->RenderHierarchicalSearch($oOutput);
  163. // - Rendering regular search
  164. $this->RenderRegularSearch($oOutput);
  165. // - Closing input group
  166. $oOutput->AddHtml('</div>');
  167. // JS FieldChange trigger (:input are not always at the same depth)
  168. // Note : Not used for that field type
  169. // Attaching JS widget
  170. $oOutput->AddJs(
  171. <<<EOF
  172. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
  173. 'validators': {$this->GetValidatorsAsJson()},
  174. 'get_current_value_callback': function(me, oEvent, oData){
  175. var value = null;
  176. value = me.element.find('#{$this->oField->GetGlobalId()}').val();
  177. return value;
  178. },
  179. 'set_current_value_callback': function(me, oEvent, oData){
  180. var sItemId = Object.keys(oData.value)[0];
  181. var sItemName = oData.value[sItemId];
  182. // Updating autocomplete field
  183. me.element.find('#{$this->oField->GetGlobalId()}').val(sItemId);
  184. me.element.find('#{$sAutocompleteFieldId}').val(sItemName);
  185. oAutocompleteSource_{$this->oField->GetId()}.index.datums[sItemId] = {id: sItemId, name: sItemName};
  186. //console.log('callback', oData);
  187. // Triggering field change event
  188. me.element.closest(".field_set").trigger("field_change", {
  189. id: me.element.find('#{$this->oField->GetGlobalId()}').attr("id"),
  190. name: me.element.find('#{$this->oField->GetGlobalId()}').attr("name"),
  191. value: me.element.find('#{$this->oField->GetGlobalId()}').val()
  192. });
  193. }
  194. });
  195. EOF
  196. );
  197. // Preparing JS part for autocomplete
  198. $oOutput->AddJs(
  199. <<<EOF
  200. var oAutocompleteSource_{$this->oField->GetId()} = new Bloodhound({
  201. queryTokenizer: Bloodhound.tokenizers.whitespace,
  202. datumTokenizer: Bloodhound.tokenizers.whitespace,
  203. remote: {
  204. url : '{$sEndpoint}',
  205. prepare: function(query, settings){
  206. settings.type = "POST";
  207. settings.contentType = "application/json; charset=UTF-8";
  208. settings.data = {
  209. sQuery: query,
  210. sFormPath: '{$this->oField->GetFormPath()}',
  211. sFieldId: '{$this->oField->GetId()}',
  212. formmanager_class: $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").closest('.portal_form_handler').portal_form_handler('getOptions').formmanager_class,
  213. formmanager_data: $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").closest('.portal_form_handler').portal_form_handler('getOptions').formmanager_data,
  214. current_values: $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").closest('.portal_form_handler').portal_form_handler('getCurrentValues')
  215. }
  216. return settings;
  217. },
  218. filter: function(response){
  219. var oItems = response.results.items;
  220. // Manualy adding data from remote to the index.datums so we can check data later
  221. for(var sItemKey in oItems)
  222. {
  223. oAutocompleteSource_{$this->oField->GetId()}.index.datums[oItems[sItemKey].id] = oItems[sItemKey];
  224. }
  225. return oItems;
  226. }
  227. }
  228. });
  229. // This check is only for IE9... Otherwise the widget is duplicated on the field causing misbehaviour.
  230. if($('#$sAutocompleteFieldId').typeahead('val') === undefined)
  231. {
  232. $('#$sAutocompleteFieldId').typeahead({
  233. hint: true,
  234. hightlight: true,
  235. minLength: {$this->oField->GetMinAutoCompleteChars()}
  236. },{
  237. name: '{$this->oField->GetId()}',
  238. source: oAutocompleteSource_{$this->oField->GetId()},
  239. limit: 20,
  240. display: 'name',
  241. templates: {
  242. suggestion: Handlebars.compile('<div>{{name}}</div>'),
  243. pending: $("#page_overlay .content_loader").prop('outerHTML'),
  244. notFound: '<div class="no_result">{$sNoResultText}</div>'
  245. }
  246. })
  247. .off('typeahead:select').on('typeahead:select', function(oEvent, oSuggestion){
  248. $('#{$this->oField->GetGlobalId()}').val(oSuggestion.id);
  249. $('#{$sAutocompleteFieldId}').val(oSuggestion.name);
  250. // Triggering set_current_value event
  251. var oValue = {};
  252. oValue[oSuggestion.id] = oSuggestion.name;
  253. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").trigger('set_current_value', {value: oValue});
  254. })
  255. .off('typeahead:change').on('typeahead:change', function(oEvent, oSuggestion){
  256. // Checking if the value is a correct value. This is necessary because the user could empty the field / remove some chars and typeahead would not update the hidden input
  257. var oDatums = oAutocompleteSource_{$this->oField->GetId()}.index.datums;
  258. var bFound = false;
  259. for(var i in oDatums)
  260. {
  261. if(oDatums[i].name == oSuggestion)
  262. {
  263. bFound = true;
  264. $('#{$this->oField->GetGlobalId()}').val(oDatums[i].id);
  265. $('#{$sAutocompleteFieldId}').val(oDatums[i].name);
  266. break;
  267. }
  268. }
  269. // Emptying the fields if value is incorrect
  270. if(!bFound)
  271. {
  272. $('#{$this->oField->GetGlobalId()}').val(0);
  273. $('#{$sAutocompleteFieldId}').val('');
  274. }
  275. });
  276. }
  277. EOF
  278. );
  279. }
  280. }
  281. $oOutput->AddHtml('</div>');
  282. // - Closing container
  283. $oOutput->AddHtml('</div>');
  284. }
  285. // ... and in read-only mode (or hidden)
  286. else
  287. {
  288. // Retrieving field value
  289. if ($this->oField->GetCurrentValue() !== null && $this->oField->GetCurrentValue() !== 0 && $this->oField->GetCurrentValue() !== '')
  290. {
  291. // Note : AllowAllData set to true here instead of checking scope's flag because we are displaying a value that has been set and validated
  292. $oFieldValue = MetaModel::GetObject($sFieldValueClass, $this->oField->GetCurrentValue(), true, true);
  293. $sFieldValue = $oFieldValue->GetName();
  294. }
  295. else
  296. {
  297. $sFieldValue = Dict::S('UI:UndefinedObject');
  298. }
  299. // Opening container
  300. $oOutput->AddHtml('<div class="form-group form_group_small">');
  301. // Showing label / value only if read-only but not hidden
  302. if (!$this->oField->GetHidden())
  303. {
  304. // Label
  305. $oOutput->AddHtml('<div class="form_field_label">');
  306. if ($this->oField->GetLabel() !== '')
  307. {
  308. $oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label">')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
  309. }
  310. $oOutput->AddHtml('</div>');
  311. // Value
  312. $oOutput->AddHtml('<div class="form_field_control">');
  313. $oOutput->AddHtml('<div class="form-control-static">' . $sFieldValue . '</div>');
  314. $oOutput->AddHtml('</div>');
  315. }
  316. // Adding hidden value
  317. $oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $this->oField->GetCurrentValue() . '" class="form-control" />');
  318. // Closing container
  319. $oOutput->AddHtml('</div>');
  320. // JS FieldChange trigger (:input are not always at the same depth)
  321. $oOutput->AddJs(
  322. <<<EOF
  323. $("#{$this->oField->GetGlobalId()}").off("change keyup").on("change keyup", function(){
  324. var me = this;
  325. $(this).closest(".field_set").trigger("field_change", {
  326. id: $(me).attr("id"),
  327. name: $(me).closest(".form_field").attr("data-field-id"),
  328. value: $(me).val()
  329. });
  330. });
  331. EOF
  332. );
  333. // Attaching JS widget
  334. $oOutput->AddJs(
  335. <<<EOF
  336. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
  337. 'validators': {$this->GetValidatorsAsJson()}
  338. });
  339. EOF
  340. );
  341. }
  342. return $oOutput;
  343. }
  344. /**
  345. * Renders an hierarchical search button
  346. *
  347. * @param RenderingOutput $oOutput
  348. */
  349. protected function RenderHierarchicalSearch(RenderingOutput &$oOutput)
  350. {
  351. if ($this->oField->GetHierarchical())
  352. {
  353. $sHierarchicalButtonId = 's_hi_' . $this->oField->GetGlobalId();
  354. $sEndpoint = str_replace('-sMode-', 'hierarchy', $this->oField->GetSearchEndpoint());
  355. $oOutput->AddHtml('<div class="input-group-addon" id="' . $sHierarchicalButtonId . '"><span class="fa fa-sitemap"></span></div>');
  356. $oOutput->AddJs(
  357. <<<EOF
  358. $('#{$sHierarchicalButtonId}').off('click').on('click', function(){
  359. // Creating a new modal
  360. // Note : This could be better if we check for an existing modal first instead of always creating a new one
  361. var oModalElem = $('#modal-for-all').clone();
  362. oModalElem.attr('id', '').attr('data-source-element', '{$sHierarchicalButtonId}').appendTo('body');
  363. // Resizing to small modal
  364. oModalElem.find('.modal-dialog').removeClass('modal-lg').addClass('modal-sm');
  365. // Loading content
  366. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  367. oModalElem.find('.modal-content').load(
  368. '{$sEndpoint}',
  369. {
  370. sFormPath: '{$this->oField->GetFormPath()}',
  371. sFieldId: '{$this->oField->GetId()}'
  372. },
  373. function(sResponseText, sStatus, oXHR){
  374. // Hiding modal in case of error as the general AJAX error handler will display a message
  375. if(sStatus === 'error')
  376. {
  377. oModalElem.modal('hide');
  378. }
  379. }
  380. );
  381. oModalElem.modal('show');
  382. });
  383. EOF
  384. );
  385. }
  386. }
  387. /**
  388. * Renders an regular search button
  389. *
  390. * @param RenderingOutput $oOutput
  391. */
  392. protected function RenderRegularSearch(RenderingOutput &$oOutput)
  393. {
  394. $sSearchButtonId = 's_rg_' . $this->oField->GetGlobalId();
  395. $sEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
  396. $oOutput->AddHtml('<div class="input-group-addon" id="' . $sSearchButtonId . '"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></div>');
  397. $oOutput->AddJs(
  398. <<<EOF
  399. $('#{$sSearchButtonId}').off('click').on('click', function(){
  400. // Creating a new modal
  401. var oModalElem;
  402. if($('.modal[data-source-element="{$sSearchButtonId}"]').length === 0)
  403. {
  404. oModalElem = $('#modal-for-all').clone();
  405. oModalElem.attr('id', '').attr('data-source-element', '{$sSearchButtonId}').appendTo('body');
  406. }
  407. else
  408. {
  409. oModalElem = $('.modal[data-source-element="{$sSearchButtonId}"]').first();
  410. }
  411. // Resizing to small modal
  412. oModalElem.find('.modal-dialog').removeClass('modal-sm').addClass('modal-lg');
  413. // Loading content
  414. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  415. oModalElem.find('.modal-content').load(
  416. '{$sEndpoint}',
  417. {
  418. sFormPath: '{$this->oField->GetFormPath()}',
  419. sFieldId: '{$this->oField->GetId()}',
  420. formmanager_class: $(this).closest('.portal_form_handler').portal_form_handler('getOptions').formmanager_class,
  421. formmanager_data: JSON.stringify($(this).closest('.portal_form_handler').portal_form_handler('getOptions').formmanager_data),
  422. current_values: $(this).closest('.portal_form_handler').portal_form_handler('getCurrentValues')
  423. },
  424. function(sResponseText, sStatus, oXHR){
  425. // Hiding modal in case of error as the general AJAX error handler will display a message
  426. if(sStatus === 'error')
  427. {
  428. oModalElem.modal('hide');
  429. }
  430. }
  431. );
  432. oModalElem.modal('show');
  433. });
  434. EOF
  435. );
  436. }
  437. }