bsselectobjectfieldrenderer.class.inc.php 19 KB

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