ui.extkeywidget.class.inc.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Class UIExtKeyWidget
  18. * UI wdiget for displaying and editing external keys when
  19. * A simple drop-down list is not enough...
  20. *
  21. * The layout is the following
  22. *
  23. * +-- #label_<id> (input)-------+ +-----------+
  24. * | | | Browse... |
  25. * +-----------------------------+ +-----------+
  26. *
  27. * And the popup dialog has the following layout:
  28. *
  29. * +------------------- ac_dlg_<id> (div)-----------+
  30. * + +--- ds_<id> (div)---------------------------+ |
  31. * | | +------------- fs_<id> (form)------------+ | |
  32. * | | | +--------+---+ | | |
  33. * | | | | Class | V | | | |
  34. * | | | +--------+---+ | | |
  35. * | | | | | |
  36. * | | | S e a r c h F o r m | | |
  37. * | | | +--------+ | | |
  38. * | | | | Search | | | |
  39. * | | | +--------+ | | |
  40. * | | +----------------------------------------+ | |
  41. * | +--------------+-dh_<id>-+--------------------+ |
  42. * | \ Search / |
  43. * | +------+ |
  44. * | +--- fr_<id> (form)--------------------------+ |
  45. * | | +------------ dr_<id> (div)--------------+ | |
  46. * | | | | | |
  47. * | | | S e a r c h R e s u l t s | | |
  48. * | | | | | |
  49. * | | +----------------------------------------+ | |
  50. * | | +--------+ +-----+ | |
  51. * | | | Cancel | | Add | | |
  52. * | | +--------+ +-----+ | |
  53. * | +--------------------------------------------+ |
  54. * +------------------------------------------------+
  55. * @author Erwan Taloc <erwan.taloc@combodo.com>
  56. * @author Romain Quetiez <romain.quetiez@combodo.com>
  57. * @author Denis Flaven <denis.flaven@combodo.com>
  58. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  59. */
  60. require_once(APPROOT.'/application/webpage.class.inc.php');
  61. require_once(APPROOT.'/application/displayblock.class.inc.php');
  62. class UIExtKeyWidget
  63. {
  64. protected $iId;
  65. protected $sTargetClass;
  66. protected $sAttCode;
  67. protected $bSearchMode;
  68. //public function __construct($sAttCode, $sClass, $sTitle, $oAllowedValues, $value, $iInputId, $bMandatory, $sNameSuffix = '', $sFieldPrefix = '', $sFormPrefix = '')
  69. static public function DisplayFromAttCode($oPage, $sAttCode, $sClass, $sTitle, $oAllowedValues, $value, $iInputId, $bMandatory, $sFieldName = '', $sFormPrefix = '', $aArgs, $bSearchMode = false)
  70. {
  71. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  72. $sTargetClass = $oAttDef->GetTargetClass();
  73. $iMaxComboLength = $oAttDef->GetMaximumComboLength();
  74. $bAllowTargetCreation = $oAttDef->AllowTargetCreation();
  75. if (!$bSearchMode)
  76. {
  77. $sDisplayStyle = $oAttDef->GetDisplayStyle();
  78. }
  79. else
  80. {
  81. $sDisplayStyle = 'select'; // In search mode, always use a drop-down list
  82. }
  83. $oWidget = new UIExtKeyWidget($sTargetClass, $iInputId, $sAttCode, $bSearchMode);
  84. return $oWidget->Display($oPage, $iMaxComboLength, $bAllowTargetCreation, $sTitle, $oAllowedValues, $value, $iInputId, $bMandatory, $sFieldName, $sFormPrefix, $aArgs, null, $sDisplayStyle);
  85. }
  86. public function __construct($sTargetClass, $iInputId, $sAttCode = '', $bSearchMode = false)
  87. {
  88. $this->sTargetClass = $sTargetClass;
  89. $this->iId = $iInputId;
  90. $this->sAttCode = $sAttCode;
  91. $this->bSearchMode = $bSearchMode;
  92. }
  93. /**
  94. * Get the HTML fragment corresponding to the linkset editing widget
  95. * @param WebPage $oP The web page used for all the output
  96. * @param Hash $aArgs Extra context arguments
  97. * @return string The HTML fragment to be inserted into the page
  98. */
  99. public function Display(WebPage $oPage, $iMaxComboLength, $bAllowTargetCreation, $sTitle, $oAllowedValues, $value, $iInputId, $bMandatory, $sFieldName, $sFormPrefix = '', $aArgs = array(), $bSearchMode = null, $sDisplayStyle = 'select')
  100. {
  101. if (!is_null($bSearchMode))
  102. {
  103. $this->bSearchMode = $bSearchMode;
  104. }
  105. $sTitle = addslashes($sTitle);
  106. $oPage->add_linked_script('../js/extkeywidget.js');
  107. $oPage->add_linked_script('../js/forms-json-utils.js');
  108. $bCreate = (!$this->bSearchMode) && (!MetaModel::IsAbstract($this->sTargetClass)) && (UserRights::IsActionAllowed($this->sTargetClass, UR_ACTION_BULK_MODIFY) && $bAllowTargetCreation);
  109. $bExtensions = true;
  110. $sMessage = Dict::S('UI:Message:EmptyList:UseSearchForm');
  111. $sAttrFieldPrefix = ($this->bSearchMode) ? '' : 'attr_';
  112. $sHTMLValue = "<span style=\"white-space:nowrap\">"; // no wrap
  113. $sFilter = addslashes($oAllowedValues->GetFilter()->ToOQL());
  114. if($this->bSearchMode)
  115. {
  116. $sWizHelper = 'null';
  117. $sWizHelperJSON = "''";
  118. $sJSSearchMode = 'true';
  119. }
  120. else
  121. {
  122. $sWizHelper = 'oWizardHelper'.$sFormPrefix;
  123. $sWizHelperJSON = $sWizHelper.'.ToJSON()';
  124. $sJSSearchMode = 'false';
  125. }
  126. if (is_null($oAllowedValues))
  127. {
  128. throw new Exception('Implementation: null value for allowed values definition');
  129. }
  130. elseif ($oAllowedValues->Count() < $iMaxComboLength)
  131. {
  132. // Discrete list of values, use a SELECT or RADIO buttons depending on the config
  133. switch($sDisplayStyle)
  134. {
  135. case 'radio':
  136. case 'radio_horizontal':
  137. case 'radio_vertical':
  138. $sValidationField = "<span id=\"v_{$this->iId}\"></span>";
  139. $sHTMLValue = '';
  140. $bVertical = ($sDisplayStyle != 'radio_horizontal');
  141. $bExtensions = false;
  142. $oAllowedValues->Rewind();
  143. $aAllowedValues = array();
  144. while($oObj = $oAllowedValues->Fetch())
  145. {
  146. $aAllowedValues[$oObj->GetKey()] = $oObj->GetName();
  147. }
  148. $sHTMLValue = $oPage->GetRadioButtons($aAllowedValues, $value, $this->iId, "{$sAttrFieldPrefix}{$sFieldName}", $bMandatory, $bVertical, $sValidationField);
  149. $aEventsList[] ='change';
  150. break;
  151. case 'select':
  152. default:
  153. $sSelectMode = 'true';
  154. $sHelpText = ''; //$this->oAttDef->GetHelpOnEdition();
  155. $sHTMLValue = "<select title=\"$sHelpText\" name=\"{$sAttrFieldPrefix}{$sFieldName}\" id=\"$this->iId\">\n";
  156. if ($this->bSearchMode)
  157. {
  158. $sDisplayValue = isset($aArgs['sDefaultValue']) ? $aArgs['sDefaultValue'] : Dict::S('UI:SearchValue:Any');
  159. $sHTMLValue .= "<option value=\"\">$sDisplayValue</option>\n";
  160. }
  161. else
  162. {
  163. $sHTMLValue .= "<option value=\"\">".Dict::S('UI:SelectOne')."</option>\n";
  164. }
  165. $oAllowedValues->Rewind();
  166. while($oObj = $oAllowedValues->Fetch())
  167. {
  168. $key = $oObj->GetKey();
  169. $display_value = $oObj->GetName();
  170. if (($oAllowedValues->Count() == 1) && ($bMandatory == 'true') )
  171. {
  172. // When there is only once choice, select it by default
  173. $sSelected = ' selected';
  174. }
  175. else
  176. {
  177. $sSelected = ($value == $key) ? ' selected' : '';
  178. }
  179. $sHTMLValue .= "<option value=\"$key\"$sSelected>$display_value</option>\n";
  180. }
  181. $sHTMLValue .= "</select>\n";
  182. $oPage->add_ready_script(
  183. <<<EOF
  184. oACWidget_{$this->iId} = new ExtKeyWidget('{$this->iId}', '{$this->sTargetClass}', '$sFilter', '$sTitle', true, $sWizHelper, '{$this->sAttCode}', $sJSSearchMode);
  185. oACWidget_{$this->iId}.emptyHtml = "<div style=\"background: #fff; border:0; text-align:center; vertical-align:middle;\"><p>$sMessage</p></div>";
  186. $('#$this->iId').bind('update', function() { oACWidget_{$this->iId}.Update(); } );
  187. $('#$this->iId').bind('change', function() { $(this).trigger('extkeychange') } );
  188. EOF
  189. );
  190. } // Switch
  191. }
  192. else
  193. {
  194. // Too many choices, use an autocomplete
  195. $sSelectMode = 'false';
  196. if (is_null($value) || ($value == 0)) // Null values are displayed as ''
  197. {
  198. $sDisplayValue = isset($aArgs['sDefaultValue']) ? $aArgs['sDefaultValue'] : '';
  199. }
  200. else
  201. {
  202. $sDisplayValue = $this->GetObjectName($value);
  203. }
  204. $iMinChars = isset($aArgs['iMinChars']) ? $aArgs['iMinChars'] : 3; //@@@ $this->oAttDef->GetMinAutoCompleteChars();
  205. $iFieldSize = isset($aArgs['iFieldSize']) ? $aArgs['iFieldSize'] : 30; //@@@ $this->oAttDef->GetMaxSize();
  206. // the input for the auto-complete
  207. $sHTMLValue = "<input count=\"".$oAllowedValues->Count()."\" type=\"text\" id=\"label_$this->iId\" size=\"$iFieldSize\" value=\"$sDisplayValue\"/>&nbsp;";
  208. $sHTMLValue .= "<img id=\"mini_search_{$this->iId}\" style=\"border:0;vertical-align:middle;cursor:pointer;\" src=\"../images/mini_search.gif\" onClick=\"oACWidget_{$this->iId}.Search();\"/>&nbsp;";
  209. // another hidden input to store & pass the object's Id
  210. $sHTMLValue .= "<input type=\"hidden\" id=\"$this->iId\" name=\"{$sAttrFieldPrefix}{$sFieldName}\" value=\"$value\" />\n";
  211. $JSSearchMode = $this->bSearchMode ? 'true' : 'false';
  212. // Scripts to start the autocomplete and bind some events to it
  213. $oPage->add_ready_script(
  214. <<<EOF
  215. oACWidget_{$this->iId} = new ExtKeyWidget('{$this->iId}', '{$this->sTargetClass}', '$sFilter', '$sTitle', false, $sWizHelper, '{$this->sAttCode}', $sJSSearchMode);
  216. oACWidget_{$this->iId}.emptyHtml = "<div style=\"background: #fff; border:0; text-align:center; vertical-align:middle;\"><p>$sMessage</p></div>";
  217. $('#label_$this->iId').autocomplete(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', { scroll:true, minChars:{$iMinChars}, autoFill:false, matchContains:true, mustMatch: true, keyHolder:'#{$this->iId}', extraParams:{operation:'ac_extkey', sTargetClass:'{$this->sTargetClass}',sFilter:'$sFilter',bSearchMode:$JSSearchMode, json: function() { return $sWizHelperJSON; } }});
  218. $('#label_$this->iId').keyup(function() { if ($(this).val() == '') { $('#$this->iId').val(''); } } ); // Useful for search forms: empty value in the "label", means no value, immediatly !
  219. $('#label_$this->iId').result( function(event, data, formatted) { OnAutoComplete('{$this->iId}', event, data, formatted); } );
  220. $('#$this->iId').bind('update', function() { oACWidget_{$this->iId}.Update(); } );
  221. if ($('#ac_dlg_{$this->iId}').length == 0)
  222. {
  223. $('body').append('<div id="ac_dlg_{$this->iId}"></div>');
  224. }
  225. EOF
  226. );
  227. }
  228. if ($bExtensions && MetaModel::IsHierarchicalClass($this->sTargetClass) !== false)
  229. {
  230. $sHTMLValue .= "<img id=\"mini_tree_{$this->iId}\" style=\"border:0;vertical-align:middle;cursor:pointer;\" src=\"../images/mini_tree.gif\" onClick=\"oACWidget_{$this->iId}.HKDisplay();\"/>&nbsp;";
  231. $oPage->add_ready_script(
  232. <<<EOF
  233. if ($('#ac_tree_{$this->iId}').length == 0)
  234. {
  235. $('body').append('<div id="ac_tree_{$this->iId}"></div>');
  236. }
  237. EOF
  238. );
  239. }
  240. if ($bCreate && $bExtensions)
  241. {
  242. $sHTMLValue .= "<img id=\"mini_add_{$this->iId}\" style=\"border:0;vertical-align:middle;cursor:pointer;\" src=\"../images/mini_add.gif\" onClick=\"oACWidget_{$this->iId}.CreateObject();\"/>&nbsp;";
  243. $oPage->add_ready_script(
  244. <<<EOF
  245. if ($('#ajax_{$this->iId}').length == 0)
  246. {
  247. $('body').append('<div id="ajax_{$this->iId}"></div>');
  248. }
  249. EOF
  250. );
  251. }
  252. if ($sDisplayStyle == 'select')
  253. {
  254. $sHTMLValue .= "<span id=\"v_{$this->iId}\"></span>";
  255. }
  256. $sHTMLValue .= "</span>"; // end of no wrap
  257. return $sHTMLValue;
  258. }
  259. public function GetSearchDialog(WebPage $oPage, $sTitle, $oCurrObject = null)
  260. {
  261. $sHTML = '<div class="wizContainer" style="vertical-align:top;"><div id="dc_'.$this->iId.'">';
  262. if ( ($oCurrObject != null) && ($this->sAttCode != ''))
  263. {
  264. $oAttDef = MetaModel::GetAttributeDef(get_class($oCurrObject), $this->sAttCode);
  265. $aParams = array('query_params' => array('this' => $oCurrObject));
  266. $oSet = $oAttDef->GetAllowedValuesAsObjectSet($aParams);
  267. $oFilter = $oSet->GetFilter();
  268. }
  269. else
  270. {
  271. $aParams = array();
  272. $oFilter = new DBObjectSearch($this->sTargetClass);
  273. }
  274. $oFilter->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', $this->bSearchMode);
  275. $oBlock = new DisplayBlock($oFilter, 'search', false, $aParams);
  276. $sHTML .= $oBlock->GetDisplay($oPage, $this->iId, array('open' => true, 'currentId' => $this->iId));
  277. $sHTML .= "<form id=\"fr_{$this->iId}\" OnSubmit=\"return oACWidget_{$this->iId}.DoOk();\">\n";
  278. $sHTML .= "<div id=\"dr_{$this->iId}\" style=\"vertical-align:top;background: #fff;height:100%;overflow:auto;padding:0;border:0;\">\n";
  279. $sHTML .= "<div style=\"background: #fff; border:0; text-align:center; vertical-align:middle;\"><p>".Dict::S('UI:Message:EmptyList:UseSearchForm')."</p></div>\n";
  280. $sHTML .= "</div>\n";
  281. $sHTML .= "<input type=\"button\" id=\"btn_cancel_{$this->iId}\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"$('#ac_dlg_{$this->iId}').dialog('close');\">&nbsp;&nbsp;";
  282. $sHTML .= "<input type=\"button\" id=\"btn_ok_{$this->iId}\" value=\"".Dict::S('UI:Button:Ok')."\" onClick=\"oACWidget_{$this->iId}.DoOk();\">";
  283. $sHTML .= "<input type=\"hidden\" id=\"count_{$this->iId}\" value=\"0\">";
  284. $sHTML .= "</form>\n";
  285. $sHTML .= '</div></div>';
  286. $sDialogTitle = addslashes($sTitle);
  287. $oPage->add_ready_script(
  288. <<<EOF
  289. $('#ac_dlg_{$this->iId}').dialog({ width: $(window).width()*0.8, height: $(window).height()*0.8, autoOpen: false, modal: true, title: '$sDialogTitle', resizeStop: oACWidget_{$this->iId}.UpdateSizes, close: oACWidget_{$this->iId}.OnClose });
  290. $('#fs_{$this->iId}').bind('submit.uiAutocomplete', oACWidget_{$this->iId}.DoSearchObjects);
  291. $('#dc_{$this->iId}').resize(oACWidget_{$this->iId}.UpdateSizes);
  292. EOF
  293. );
  294. $oPage->add($sHTML);
  295. }
  296. /**
  297. * Search for objects to be selected
  298. * @param WebPage $oP The page used for the output (usually an AjaxWebPage)
  299. * @param string $sRemoteClass Name of the "remote" class to perform the search on, must be a derived class of m_sRemoteClass
  300. * @param Array $aAlreadyLinkedIds List of IDs of objects of "remote" class already linked, to be filtered out of the search
  301. */
  302. public function SearchObjectsToSelect(WebPage $oP, $sFilter, $sRemoteClass = '', $oObj = null)
  303. {
  304. if (is_null($sFilter))
  305. {
  306. throw new Exception('Implementation: null value for allowed values definition');
  307. }
  308. try
  309. {
  310. $oFilter = DBObjectSearch::FromOQL($sFilter);
  311. $oFilter->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', $this->bSearchMode);
  312. $oBlock = new DisplayBlock($oFilter, 'list', false, array('query_params' => array('this' => $oObj)));
  313. $oBlock->Display($oP, $this->iId.'_results', array('this' => $oObj, 'cssCount'=> '#count_'.$this->iId, 'menu' => false, 'selection_mode' => true, 'selection_type' => 'single')); // Don't display the 'Actions' menu on the results
  314. }
  315. catch(MissingQueryArgument $e)
  316. {
  317. // When used in a search form the $this parameter may be missing, in this case return all possible values...
  318. // TODO check if we can improve this behavior...
  319. $sOQL = 'SELECT '.$sRemoteClass;
  320. $oFilter = DBObjectSearch::FromOQL($sOQL);
  321. $oFilter->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', $this->bSearchMode);
  322. //$oBlock = new DisplayBlock($oFilter, 'list', false);
  323. //$oBlock->Display($oP, $this->iId.'_results', array('cssCount'=> '#count_'.$this->iId, 'menu' => false, 'selection_mode' => true, 'selection_type' => 'single')); // Don't display the 'Actions' menu on the results
  324. }
  325. }
  326. /**
  327. * Search for objects to be selected
  328. * @param WebPage $oP The page used for the output (usually an AjaxWebPage)
  329. * @param string $sFilter The OQL expression used to define/limit limit the scope of possible values
  330. * @param DBObject $oObj The current object for the OQL context
  331. * @param string $sContains The text of the autocomplete to filter the results
  332. */
  333. public function AutoComplete(WebPage $oP, $sFilter, $oObj = null, $sContains)
  334. {
  335. if (is_null($sFilter))
  336. {
  337. throw new Exception('Implementation: null value for allowed values definition');
  338. }
  339. $oValuesSet = new ValueSetObjects($sFilter, 'friendlyname'); // Bypass GetName() to avoid the encoding by htmlentities
  340. $oValuesSet->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', $this->bSearchMode);
  341. $aValues = $oValuesSet->GetValues(array('this' => $oObj), $sContains);
  342. foreach($aValues as $sKey => $sFriendlyName)
  343. {
  344. $oP->add(trim($sFriendlyName)."\t".$sKey."\n");
  345. }
  346. }
  347. /**
  348. * Get the display name of the selected object, to fill back the autocomplete
  349. */
  350. public function GetObjectName($iObjId)
  351. {
  352. $aModifierProps = array();
  353. $aModifierProps['UserRightsGetSelectFilter']['bSearchMode'] = $this->bSearchMode;
  354. $oObj = MetaModel::GetObject($this->sTargetClass, $iObjId, false, false, $aModifierProps);
  355. if ($oObj)
  356. {
  357. return $oObj->GetName();
  358. }
  359. else
  360. {
  361. return '';
  362. }
  363. }
  364. /**
  365. * Get the form to create a new object of the 'target' class
  366. */
  367. public function GetObjectCreationForm(WebPage $oPage, $oCurrObject)
  368. {
  369. // Set all the default values in an object and clone this "default" object
  370. $oNewObj = MetaModel::NewObject($this->sTargetClass);
  371. // 1st - set context values
  372. $oAppContext = new ApplicationContext();
  373. $oAppContext->InitObjectFromContext($oNewObj);
  374. // 2nd set the default values from the constraint on the external key... if any
  375. if ( ($oCurrObject != null) && ($this->sAttCode != ''))
  376. {
  377. $oAttDef = MetaModel::GetAttributeDef(get_class($oCurrObject), $this->sAttCode);
  378. $aParams = array('this' => $oCurrObject);
  379. $oSet = $oAttDef->GetAllowedValuesAsObjectSet($aParams);
  380. $aConsts = $oSet->ListConstantFields();
  381. $sClassAlias = $oSet->GetFilter()->GetClassAlias();
  382. if (isset($aConsts[$sClassAlias]))
  383. {
  384. foreach($aConsts[$sClassAlias] as $sAttCode => $value)
  385. {
  386. $oNewObj->Set($sAttCode, $value);
  387. }
  388. }
  389. }
  390. // 3rd - set values from the page argument 'default'
  391. $oNewObj->UpdateObjectFromArg('default');
  392. $sDialogTitle = addslashes($this->sTitle);
  393. $oPage->add('<div id="ac_create_'.$this->iId.'"><div class="wizContainer" style="vertical-align:top;"><div id="dcr_'.$this->iId.'">');
  394. $oPage->add("<h1>".MetaModel::GetClassIcon($this->sTargetClass)."&nbsp;".Dict::Format('UI:CreationTitle_Class', MetaModel::GetName($this->sTargetClass))."</h1>\n");
  395. cmdbAbstractObject::DisplayCreationForm($oPage, $this->sTargetClass, $oNewObj, array(), array('formPrefix' => $this->iId, 'noRelations' => true));
  396. $oPage->add('</div></div></div>');
  397. // $oPage->add_ready_script("\$('#ac_create_$this->iId').dialog({ width: $(window).width()*0.8, height: 'auto', autoOpen: false, modal: true, title: '$sDialogTitle'});\n");
  398. $oPage->add_ready_script("\$('#ac_create_$this->iId').dialog({ width: 'auto', height: 'auto', autoOpen: false, modal: true, title: '$sDialogTitle'});\n");
  399. $oPage->add_ready_script("$('#dcr_{$this->iId} form').removeAttr('onsubmit');");
  400. $oPage->add_ready_script("$('#dcr_{$this->iId} form').bind('submit.uilinksWizard', oACWidget_{$this->iId}.DoCreateObject);");
  401. }
  402. /**
  403. * Display the hierarchy of the 'target' class
  404. */
  405. public function DisplayHierarchy(WebPage $oPage, $sFilter, $currValue, $oObj)
  406. {
  407. $sDialogTitle = addslashes(Dict::Format('UI:HierarchyOf_Class', MetaModel::GetName($this->sTargetClass)));
  408. $oPage->add('<div id="dlg_tree_'.$this->iId.'"><div class="wizContainer" style="vertical-align:top;"><div style="overflow:auto;background:#fff;margin-bottom:5px;" id="tree_'.$this->iId.'">');
  409. $oPage->add('<table style="width:100%"><tr><td>');
  410. if (is_null($sFilter))
  411. {
  412. throw new Exception('Implementation: null value for allowed values definition');
  413. }
  414. try
  415. {
  416. $oFilter = DBObjectSearch::FromOQL($sFilter);
  417. $oFilter->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', $this->bSearchMode);
  418. $oSet = new DBObjectSet($oFilter, array(), array('this' => $oObj));
  419. }
  420. catch(MissingQueryArgument $e)
  421. {
  422. // When used in a search form the $this parameter may be missing, in this case return all possible values...
  423. // TODO check if we can improve this behavior...
  424. $sOQL = 'SELECT '.$this->m_sTargetClass;
  425. $oFilter = DBObjectSearch::FromOQL($sOQL);
  426. $oFilter->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', $this->bSearchMode);
  427. $oSet = new DBObjectSet($oFilter);
  428. }
  429. $sHKAttCode = MetaModel::IsHierarchicalClass($this->sTargetClass);
  430. $this->DumpTree($oPage, $oSet, $sHKAttCode, $currValue);
  431. $oPage->add('</td></tr></table>');
  432. $oPage->add('</div>');
  433. $oPage->add("<input type=\"button\" id=\"btn_cancel_{$this->iId}\" value=\"".Dict::S('UI:Button:Cancel')."\" onClick=\"$('#dlg_tree_{$this->iId}').dialog('close');\">&nbsp;&nbsp;");
  434. $oPage->add("<input type=\"button\" id=\"btn_ok_{$this->iId}\" value=\"".Dict::S('UI:Button:Ok')."\" onClick=\"oACWidget_{$this->iId}.DoHKOk();\">");
  435. $oPage->add('</div></div>');
  436. $oPage->add_ready_script("\$('#tree_$this->iId ul').treeview();\n");
  437. $oPage->add_ready_script("\$('#dlg_tree_$this->iId').dialog({ width: 'auto', height: 'auto', autoOpen: true, modal: true, title: '$sDialogTitle', resizeStop: oACWidget_{$this->iId}.OnHKResize, close: oACWidget_{$this->iId}.OnHKClose });\n");
  438. }
  439. /**
  440. * Get the form to create a new object of the 'target' class
  441. */
  442. public function DoCreateObject($oPage)
  443. {
  444. $oObj = MetaModel::NewObject($this->sTargetClass);
  445. $aErrors = $oObj->UpdateObjectFromPostedForm($this->iId);
  446. if (count($aErrors) == 0)
  447. {
  448. $oMyChange = MetaModel::NewObject("CMDBChange");
  449. $oMyChange->Set("date", time());
  450. $sUserString = CMDBChange::GetCurrentUserName();
  451. $oMyChange->Set("userinfo", $sUserString);
  452. $iChangeId = $oMyChange->DBInsert();
  453. $oObj->DBInsertTracked($oMyChange);
  454. return array('name' => $oObj->GetName(), 'id' => $oObj->GetKey());
  455. }
  456. else
  457. {
  458. return array('name' => implode(' ', $aErrors), 'id' => 0);
  459. }
  460. }
  461. function DumpTree($oP, $oSet, $sParentAttCode, $currValue)
  462. {
  463. $aTree = array();
  464. $aNodes = array();
  465. while($oObj = $oSet->Fetch())
  466. {
  467. $iParentId = $oObj->Get($sParentAttCode);
  468. if (!isset($aTree[$iParentId]))
  469. {
  470. $aTree[$iParentId] = array();
  471. }
  472. $aTree[$iParentId][$oObj->GetKey()] = $oObj->GetName();
  473. $aNodes[$oObj->GetKey()] = $oObj;
  474. }
  475. $aParents = array_keys($aTree);
  476. $aRoots = array();
  477. foreach($aParents as $id)
  478. {
  479. if (!array_key_exists($id, $aNodes))
  480. {
  481. $aRoots[] = $id;
  482. }
  483. }
  484. foreach($aRoots as $iRootId)
  485. {
  486. $this->DumpNodes($oP, $iRootId, $aTree, $aNodes, $currValue);
  487. }
  488. }
  489. function DumpNodes($oP, $iRootId, $aTree, $aNodes, $currValue)
  490. {
  491. $bSelect = true;
  492. $bMultiple = false;
  493. $sSelect = '';
  494. if (array_key_exists($iRootId, $aTree))
  495. {
  496. $aSortedRoots = $aTree[$iRootId];
  497. asort($aSortedRoots);
  498. $oP->add("<ul>\n");
  499. foreach($aSortedRoots as $id => $sName)
  500. {
  501. if ($bSelect)
  502. {
  503. $sChecked = ($aNodes[$id]->GetKey() == $currValue) ? 'checked' : '';
  504. if ($bMultiple)
  505. {
  506. $sSelect = '<input type="checkbox" value="'.$aNodes[$id]->GetKey().'" name="selectObject[]" '.$sChecked.'>&nbsp;';
  507. }
  508. else
  509. {
  510. $sSelect = '<input type="radio" value="'.$aNodes[$id]->GetKey().'" name="selectObject" '.$sChecked.'>&nbsp;';
  511. }
  512. }
  513. $oP->add('<li>'.$sSelect.$aNodes[$id]->GetHyperlink());
  514. $this->DumpNodes($oP, $id, $aTree, $aNodes, $currValue);
  515. $oP->add("</li>\n");
  516. }
  517. $oP->add("</ul>\n");
  518. }
  519. }
  520. }
  521. ?>