🎨 📝 format & add comment

This commit is contained in:
Pierre Goiffon
2020-08-12 10:01:38 +02:00
parent 44e188fa2c
commit 7d7270296e
7 changed files with 474 additions and 488 deletions

View File

@@ -2332,23 +2332,23 @@ EOF
$oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/form_field.js'); $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/form_field.js');
$oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/subform_field.js'); $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'js/subform_field.js');
$oPage->add_ready_script( $oPage->add_ready_script(
<<<EOF <<<JS
$('#{$iId}_field_set').field_set($sFieldSetOptions); $('#{$iId}_field_set').field_set($sFieldSetOptions);
$('#{$iId}_console_form').console_form_handler($sFormHandlerOptions); $('#{$iId}_console_form').console_form_handler($sFormHandlerOptions);
$('#{$iId}_console_form').console_form_handler('alignColumns'); $('#{$iId}_console_form').console_form_handler('alignColumns');
$('#{$iId}_console_form').console_form_handler('option', 'field_set', $('#{$iId}_field_set')); $('#{$iId}_console_form').console_form_handler('option', 'field_set', $('#{$iId}_field_set'));
// field_change must be processed to refresh the hidden value at anytime // field_change must be processed to refresh the hidden value at anytime
$('#{$iId}_console_form').bind('value_change', function() { $('#{$iId}').val(JSON.stringify($('#{$iId}_field_set').triggerHandler('get_current_values'))); }); $('#{$iId}_console_form').bind('value_change', function() { $('#{$iId}').val(JSON.stringify($('#{$iId}_field_set').triggerHandler('get_current_values'))); });
// Initialize the hidden value with current state // Initialize the hidden value with current state
// update_value is triggered when preparing the wizard helper object for ajax calls // update_value is triggered when preparing the wizard helper object for ajax calls
$('#{$iId}').bind('update_value', function() { $(this).val(JSON.stringify($('#{$iId}_field_set').triggerHandler('get_current_values'))); }); $('#{$iId}').bind('update_value', function() { $(this).val(JSON.stringify($('#{$iId}_field_set').triggerHandler('get_current_values'))); });
// validate is triggered by CheckFields, on all the input fields, once at page init and once before submitting the form // validate is triggered by CheckFields, on all the input fields, once at page init and once before submitting the form
$('#{$iId}').bind('validate', function(evt, sFormId) { $('#{$iId}').bind('validate', function(evt, sFormId) {
$(this).val(JSON.stringify($('#{$iId}_field_set').triggerHandler('get_current_values'))); $(this).val(JSON.stringify($('#{$iId}_field_set').triggerHandler('get_current_values')));
return ValidateCustomFields('$iId', sFormId); // Custom validation function return ValidateCustomFields('$iId', sFormId); // Custom validation function
}); });
EOF JS
); );
break; break;
@@ -2479,8 +2479,7 @@ EOF
$oPage->add_ready_script("$('#$sFieldToValidateId').bind('".implode(' ', $oPage->add_ready_script("$('#$sFieldToValidateId').bind('".implode(' ',
$aEventsList)."', function(evt, sFormId) { return ValidateField('$sFieldToValidateId', '$sPattern', $bMandatory, sFormId, $sNullValue, $sOriginalValue) } );\n"); // Bind to a custom event: validate $aEventsList)."', function(evt, sFormId) { return ValidateField('$sFieldToValidateId', '$sPattern', $bMandatory, sFormId, $sNullValue, $sOriginalValue) } );\n"); // Bind to a custom event: validate
} }
$aDependencies = MetaModel::GetDependentAttributes($sClass, $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that depend on the current one
$sAttCode); // List of attributes that depend on the current one
if (count($aDependencies) > 0) if (count($aDependencies) > 0)
{ {
// Unbind first to avoid duplicate event handlers in case of reload of the whole (or part of the) form // Unbind first to avoid duplicate event handlers in case of reload of the whole (or part of the) form

View File

@@ -359,20 +359,21 @@ EOF
$bDoSearch = !utils::IsHighCardinality($this->m_sRemoteClass); $bDoSearch = !utils::IsHighCardinality($this->m_sRemoteClass);
$sJSDoSearch = $bDoSearch ? 'true' : 'false'; $sJSDoSearch = $bDoSearch ? 'true' : 'false';
$sWizHelper = 'oWizardHelper'.$sFormPrefix; $sWizHelper = 'oWizardHelper'.$sFormPrefix;
$oPage->add_ready_script(<<<EOF $oPage->add_ready_script(<<<JS
oWidget{$this->m_iInputId} = new LinksWidget('{$this->m_sAttCode}{$this->m_sNameSuffix}', '{$this->m_sClass}', '{$this->m_sAttCode}', '{$this->m_iInputId}', '{$this->m_sNameSuffix}', $sDuplicates, $sWizHelper, '{$this->m_sExtKeyToRemote}', $sJSDoSearch); oWidget{$this->m_iInputId} = new LinksWidget('{$this->m_sAttCode}{$this->m_sNameSuffix}', '{$this->m_sClass}', '{$this->m_sAttCode}', '{$this->m_iInputId}', '{$this->m_sNameSuffix}', $sDuplicates, $sWizHelper, '{$this->m_sExtKeyToRemote}', $sJSDoSearch);
oWidget{$this->m_iInputId}.Init(); oWidget{$this->m_iInputId}.Init();
EOF JS
); );
while($oCurrentLink = $oValue->Fetch()) while ($oCurrentLink = $oValue->Fetch())
{ {
// We try to retrieve the remote object as usual // We try to retrieve the remote object as usual
$oLinkedObj = MetaModel::GetObject($this->m_sRemoteClass, $oCurrentLink->Get($this->m_sExtKeyToRemote), false /* Must not be found */); $oLinkedObj = MetaModel::GetObject($this->m_sRemoteClass, $oCurrentLink->Get($this->m_sExtKeyToRemote),
false /* Must not be found */);
// If successful, it means that we can edit its link // If successful, it means that we can edit its link
if($oLinkedObj !== null) if ($oLinkedObj !== null)
{ {
$bReadOnly = false; $bReadOnly = false;
} }
// Else we retrieve it without restrictions (silos) and will display its link as readonly // Else we retrieve it without restrictions (silos) and will display its link as readonly
else else

View File

@@ -15,8 +15,7 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with iTop. If not, see <http://www.gnu.org/licenses/> // along with iTop. If not, see <http://www.gnu.org/licenses/>
function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper, sAttCode, bSearchMode, bDoSearch) function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper, sAttCode, bSearchMode, bDoSearch) {
{
this.id = id; this.id = id;
this.sOriginalTargetClass = sTargetClass; this.sOriginalTargetClass = sTargetClass;
this.sTargetClass = sTargetClass; this.sTargetClass = sTargetClass;
@@ -31,11 +30,10 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
this.bSearchMode = bSearchMode; // true if selecting a value in the context of a search form this.bSearchMode = bSearchMode; // true if selecting a value in the context of a search form
this.bDoSearch = bDoSearch; // false if the search is not launched this.bDoSearch = bDoSearch; // false if the search is not launched
var me = this; var me = this;
this.Init = function() this.Init = function () {
{
// make sure that the form is clean // make sure that the form is clean
$('#'+this.id+'_btnRemove').prop('disabled',true); $('#'+this.id+'_btnRemove').prop('disabled', true);
$('#'+this.id+'_linksToRemove').val(''); $('#'+this.id+'_linksToRemove').val('');
} }
this.AddSelectize = function(options, initValue) this.AddSelectize = function(options, initValue)
@@ -153,35 +151,36 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
.appendTo(ul); .appendTo(ul);
}; };
$('#label_'+me.id).focus(function(){ $('#label_'+me.id).focus(function () {
// track whether the field has focus, we shouldn't process any // track whether the field has focus, we shouldn't process any
// results if the field no longer has focus // results if the field no longer has focus
hasFocus++; hasFocus++;
}).blur(function() { }).blur(function () {
hasFocus = 0; hasFocus = 0;
}).click( }).click(
function() { function () {
if(hasFocus++>1) if (hasFocus++ > 1)
{ {
$('#label_'+me.id).autocomplete( "search"); $('#label_'+me.id).autocomplete("search");
} }
}); });
}; };
this.StopPendingRequest = function() this.StopPendingRequest = function () {
{
if (me.ajax_request) if (me.ajax_request)
{ {
me.ajax_request.abort(); me.ajax_request.abort();
me.ajax_request = null; me.ajax_request = null;
} }
}; };
this.Search = function() this.Search = function () {
{ if ($('#'+me.id).prop('disabled'))
if($('#'+me.id).prop('disabled')) return; // Disabled, do nothing {
return;
} // Disabled, do nothing
var value = $('#'+me.id).val(); // Current value var value = $('#'+me.id).val(); // Current value
// Query the server to get the form to search for target objects // Query the server to get the form to search for target objects
if (me.bSelectMode) if (me.bSelectMode)
{ {
@@ -191,15 +190,16 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
{ {
$('#label_'+me.id).addClass('ac_dlg_loading'); $('#label_'+me.id).addClass('ac_dlg_loading');
} }
var theMap = { sAttCode: me.sAttCode, var theMap = {
iInputId: me.id, sAttCode: me.sAttCode,
sTitle: me.sTitle, iInputId: me.id,
sAttCode: me.sAttCode, sTitle: me.sTitle,
sTargetClass: me.sTargetClass, sAttCode: me.sAttCode,
bSearchMode: me.bSearchMode, sTargetClass: me.sTargetClass,
operation: 'objectSearchForm' bSearchMode: me.bSearchMode,
}; operation: 'objectSearchForm'
};
if (me.oWizardHelper == null) if (me.oWizardHelper == null)
{ {
theMap['json'] = ''; theMap['json'] = '';
@@ -214,17 +214,16 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
// Make sure that we cancel any pending request before issuing another // Make sure that we cancel any pending request before issuing another
// since responses may arrive in arbitrary order // since responses may arrive in arbitrary order
me.StopPendingRequest(); me.StopPendingRequest();
// Run the query and get the result back directly in HTML // Run the query and get the result back directly in HTML
me.ajax_request = $.post( AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap, me.ajax_request = $.post(AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap,
function(data) function (data) {
{
$('#ac_dlg_'+me.id).html(data); $('#ac_dlg_'+me.id).html(data);
$('#ac_dlg_'+me.id).dialog('open'); $('#ac_dlg_'+me.id).dialog('open');
me.UpdateSizes(); me.UpdateSizes();
me.UpdateButtons(); me.UpdateButtons();
me.ajax_request = null; me.ajax_request = null;
$('#count_'+me.id).change(function(){ $('#count_'+me.id).change(function () {
me.UpdateButtons(); me.UpdateButtons();
}); });
if (me.bDoSearch) if (me.bDoSearch)
@@ -235,9 +234,8 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
'html' 'html'
); );
}; };
this.UpdateSizes = function() this.UpdateSizes = function () {
{
var dlg = $('#ac_dlg_'+me.id); var dlg = $('#ac_dlg_'+me.id);
// Adjust the dialog's size to fit into the screen // Adjust the dialog's size to fit into the screen
if (dlg.width() > ($(window).width()-40)) if (dlg.width() > ($(window).width()-40))
@@ -252,7 +250,7 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
var results = $('#dr_'+me.id); var results = $('#dr_'+me.id);
var oPadding = {}; var oPadding = {};
var aKeys = ['top', 'right', 'bottom', 'left']; var aKeys = ['top', 'right', 'bottom', 'left'];
for(k in aKeys) for (k in aKeys)
{ {
oPadding[aKeys[k]] = 0; oPadding[aKeys[k]] = 0;
if (dlg.css('padding-'+aKeys[k])) if (dlg.css('padding-'+aKeys[k]))
@@ -260,14 +258,13 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
oPadding[aKeys[k]] = parseInt(dlg.css('padding-'+aKeys[k]).replace('px', '')); oPadding[aKeys[k]] = parseInt(dlg.css('padding-'+aKeys[k]).replace('px', ''));
} }
} }
width = dlg.innerWidth() - oPadding['right'] - oPadding['left'] - 22; // 5 (margin-left) + 5 (padding-left) + 5 (padding-right) + 5 (margin-right) + 2 for rounding ! width = dlg.innerWidth()-oPadding['right']-oPadding['left']-22; // 5 (margin-left) + 5 (padding-left) + 5 (padding-right) + 5 (margin-right) + 2 for rounding !
height = dlg.innerHeight() - oPadding['top'] - oPadding['bottom'] -22; height = dlg.innerHeight()-oPadding['top']-oPadding['bottom']-22;
form_height = searchForm.outerHeight(); form_height = searchForm.outerHeight();
results.height(height - form_height - 40); // Leave some space for the buttons results.height(height-form_height-40); // Leave some space for the buttons
}; };
this.UpdateButtons = function() this.UpdateButtons = function () {
{
var okBtn = $('#btn_ok_'+me.id); var okBtn = $('#btn_ok_'+me.id);
if ($('#count_'+me.id).val() > 0) if ($('#count_'+me.id).val() > 0)
{ {
@@ -278,27 +275,27 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
okBtn.prop('disabled', true); okBtn.prop('disabled', true);
} }
}; };
this.DoSearchObjects = function(id) this.DoSearchObjects = function (id) {
{ var theMap = {
var theMap = { sTargetClass: me.sTargetClass, sTargetClass: me.sTargetClass,
iInputId: me.id, iInputId: me.id,
sFilter: me.sFilter, sFilter: me.sFilter,
bSearchMode: me.bSearchMode bSearchMode: me.bSearchMode
}; };
// Gather the parameters from the search form // Gather the parameters from the search form
$('#fs_'+me.id+' :input').each( function() { $('#fs_'+me.id+' :input').each(function () {
if (this.name != '') if (this.name != '')
{ {
var val = $(this).val(); // supports multiselect as well var val = $(this).val(); // supports multiselect as well
if (val !== null) if (val !== null)
{ {
theMap[this.name] = val; theMap[this.name] = val;
} }
} }
}); });
if (me.oWizardHelper == null) if (me.oWizardHelper == null)
{ {
theMap['json'] = ''; theMap['json'] = '';
@@ -309,12 +306,12 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
me.oWizardHelper.UpdateWizard(); me.oWizardHelper.UpdateWizard();
theMap['json'] = me.oWizardHelper.ToJSON(); theMap['json'] = me.oWizardHelper.ToJSON();
} }
theMap['sRemoteClass'] = theMap['class']; // swap 'class' (defined in the form) and 'remoteClass' theMap['sRemoteClass'] = theMap['class']; // swap 'class' (defined in the form) and 'remoteClass'
theMap.operation = 'searchObjectsToSelect'; // Override what is defined in the form itself theMap.operation = 'searchObjectsToSelect'; // Override what is defined in the form itself
theMap.sAttCode = me.sAttCode, theMap.sAttCode = me.sAttCode,
sSearchAreaId = '#dr_'+me.id; sSearchAreaId = '#dr_'+me.id;
//$(sSearchAreaId).html('<div style="text-align:center;width:100%;height:24px;vertical-align:middle;"><img src="../images/indicator.gif" /></div>'); //$(sSearchAreaId).html('<div style="text-align:center;width:100%;height:24px;vertical-align:middle;"><img src="../images/indicator.gif" /></div>');
$(sSearchAreaId).block(); $(sSearchAreaId).block();
me.UpdateButtons(); me.UpdateButtons();
@@ -322,14 +319,15 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
// Make sure that we cancel any pending request before issuing another // Make sure that we cancel any pending request before issuing another
// since responses may arrive in arbitrary order // since responses may arrive in arbitrary order
me.StopPendingRequest(); me.StopPendingRequest();
// Run the query and display the results // Run the query and display the results
me.ajax_request = $.post( AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap, me.ajax_request = $.post(AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap,
function(data) function (data) {
{
$(sSearchAreaId).html(data); $(sSearchAreaId).html(data);
$(sSearchAreaId+' .listResults').tableHover(); $(sSearchAreaId+' .listResults').tableHover();
$('#fr_'+me.id+' input:radio').click(function() { me.UpdateButtons(); }); $('#fr_'+me.id+' input:radio').click(function () {
me.UpdateButtons();
});
me.UpdateButtons(); me.UpdateButtons();
me.ajax_request = null; me.ajax_request = null;
me.UpdateSizes(); me.UpdateSizes();
@@ -339,9 +337,8 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
return false; // Don't submit the form, stay in the current page ! return false; // Don't submit the form, stay in the current page !
}; };
this.DoOk = function() this.DoOk = function () {
{
var s = $('#'+me.id+'_results').find(':input[name^=storedSelection]'); var s = $('#'+me.id+'_results').find(':input[name^=storedSelection]');
var iObjectId = 0; var iObjectId = 0;
if (s.length > 0) if (s.length > 0)
@@ -356,22 +353,22 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
$('#label_'+this.id).addClass('ac_dlg_loading'); $('#label_'+this.id).addClass('ac_dlg_loading');
// Query the server again to get the display name of the selected object // Query the server again to get the display name of the selected object
var theMap = { sTargetClass: me.sTargetClass, var theMap = {
iInputId: me.id, sTargetClass: me.sTargetClass,
iObjectId: iObjectId, iInputId: me.id,
sAttCode: me.sAttCode, iObjectId: iObjectId,
bSearchMode: me.bSearchMode, sAttCode: me.sAttCode,
operation: 'getObjectName' bSearchMode: me.bSearchMode,
}; operation: 'getObjectName'
};
// Make sure that we cancel any pending request before issuing another // Make sure that we cancel any pending request before issuing another
// since responses may arrive in arbitrary order // since responses may arrive in arbitrary order
me.StopPendingRequest(); me.StopPendingRequest();
// Run the query and get the result back directly in JSON // Run the query and get the result back directly in JSON
me.ajax_request = $.post( AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap, me.ajax_request = $.post(AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap,
function(data) function (data) {
{
var oTemp = $('<div>'+data.name+'</div>'); var oTemp = $('<div>'+data.name+'</div>');
var txt = oTemp.text(); // this causes HTML entities to be interpreted var txt = oTemp.text(); // this causes HTML entities to be interpreted
$('#label_'+me.id).val(txt); $('#label_'+me.id).val(txt);
@@ -383,21 +380,20 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
$('#'+me.id).trigger('validate'); $('#'+me.id).trigger('validate');
$('#'+me.id).trigger('extkeychange'); $('#'+me.id).trigger('extkeychange');
$('#'+me.id).trigger('change'); $('#'+me.id).trigger('change');
} }
$('#label_'+me.id).focus(); $('#label_'+me.id).focus();
me.ajax_request = null; me.ajax_request = null;
}, },
'json' 'json'
); );
return false; // Do NOT submit the form in case we are called by OnSubmit... return false; // Do NOT submit the form in case we are called by OnSubmit...
}; };
// Workaround for a ui.jquery limitation: if the content of // Workaround for a ui.jquery limitation: if the content of
// the dialog contains many INPUTs, closing and opening the // the dialog contains many INPUTs, closing and opening the
// dialog is very slow. So empty it each time. // dialog is very slow. So empty it each time.
this.OnClose = function() this.OnClose = function () {
{
me.StopPendingRequest(); me.StopPendingRequest();
// called by the dialog, so in the context 'this' points to the jQueryObject // called by the dialog, so in the context 'this' points to the jQueryObject
if (me.emptyOnClose) if (me.emptyOnClose)
@@ -409,33 +405,36 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
me.ajax_request = null; me.ajax_request = null;
}; };
this.SelectObjectClass = function(oWizHelper) this.SelectObjectClass = function (oWizHelper) {
{ // Resetting target class to its original value
// Resetting target class to its original value // (If not done, closing the dialog and trying to create a object again
// (If not done, closing the dialog and trying to create a object again // will force it be of the same class as the previous call)
// will force it be of the same class as the previous call) me.sTargetClass = me.sOriginalTargetClass;
me.sTargetClass = me.sOriginalTargetClass;
me.CreateObject(oWizHelper); me.CreateObject(oWizHelper);
}; };
this.DoSelectObjectClass = function() this.DoSelectObjectClass = function () {
{
// Retrieving selected value // Retrieving selected value
var oSelectedClass = $('#ac_create_'+me.id+' select'); var oSelectedClass = $('#ac_create_'+me.id+' select');
if(oSelectedClass.length !== 1) return; if (oSelectedClass.length !== 1)
{
return;
}
// Setting new target class // Setting new target class
me.sTargetClass = oSelectedClass.val(); me.sTargetClass = oSelectedClass.val();
// Opening real creation form // Opening real creation form
$('#ac_create_'+me.id).dialog('close'); $('#ac_create_'+me.id).dialog('close');
me.CreateObject(); me.CreateObject();
}; };
this.CreateObject = function(oWizHelper) this.CreateObject = function (oWizHelper) {
{ if ($('#'+me.id).prop('disabled'))
if($('#'+me.id).prop('disabled')) return; // Disabled, do nothing {
return;
} // Disabled, do nothing
// Query the server to get the form to create a target object // Query the server to get the form to create a target object
if (me.bSelectMode) if (me.bSelectMode)
{ {
@@ -446,26 +445,26 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
$('#label_'+me.id).addClass('ac_dlg_loading'); $('#label_'+me.id).addClass('ac_dlg_loading');
} }
me.oWizardHelper.UpdateWizard(); me.oWizardHelper.UpdateWizard();
var theMap = { sTargetClass: me.sTargetClass, var theMap = {
iInputId: me.id, sTargetClass: me.sTargetClass,
sAttCode: me.sAttCode, iInputId: me.id,
'json': me.oWizardHelper.ToJSON(), sAttCode: me.sAttCode,
operation: 'objectCreationForm' 'json': me.oWizardHelper.ToJSON(),
}; operation: 'objectCreationForm'
};
// Make sure that we cancel any pending request before issuing another // Make sure that we cancel any pending request before issuing another
// since responses may arrive in arbitrary order // since responses may arrive in arbitrary order
me.StopPendingRequest(); me.StopPendingRequest();
// Run the query and get the result back directly in HTML // Run the query and get the result back directly in HTML
me.ajax_request = $.post( AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap, me.ajax_request = $.post(AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap,
function(data) function (data) {
{
$('#ajax_'+me.id).html(data); $('#ajax_'+me.id).html(data);
$('#ac_create_'+me.id).dialog('open'); $('#ac_create_'+me.id).dialog('open');
$('#ac_create_'+me.id).dialog( "option", "close", me.OnCloseCreateObject ); $('#ac_create_'+me.id).dialog("option", "close", me.OnCloseCreateObject);
// Modify the action of the cancel button // Modify the action of the cancel button
$('#ac_create_'+me.id+' button.cancel').unbind('click').click( me.CloseCreateObject ); $('#ac_create_'+me.id+' button.cancel').unbind('click').click(me.CloseCreateObject);
me.ajax_request = null; me.ajax_request = null;
// Adjust the dialog's size to fit into the screen // Adjust the dialog's size to fit into the screen
if ($('#ac_create_'+me.id).width() > ($(window).width()-40)) if ($('#ac_create_'+me.id).width() > ($(window).width()-40))
@@ -480,14 +479,12 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
'html' 'html'
); );
}; };
this.CloseCreateObject = function() this.CloseCreateObject = function () {
{ $('#ac_create_'+me.id).dialog("close");
$('#ac_create_'+me.id).dialog( "close" );
}; };
this.OnCloseCreateObject = function() this.OnCloseCreateObject = function () {
{
if (me.bSelectMode) if (me.bSelectMode)
{ {
$('#fstatus_'+me.id).html(''); $('#fstatus_'+me.id).html('');
@@ -501,24 +498,23 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
$('#ac_create_'+me.id).remove(); $('#ac_create_'+me.id).remove();
$('#ajax_'+me.id).html(''); $('#ajax_'+me.id).html('');
}; };
this.DoCreateObject = function() this.DoCreateObject = function () {
{
var sFormId = $('#dcr_'+me.id+' form').attr('id'); var sFormId = $('#dcr_'+me.id+' form').attr('id');
if (CheckFields(sFormId, true)) if (CheckFields(sFormId, true))
{ {
$('#'+sFormId).block(); $('#'+sFormId).block();
var theMap = { sTargetClass: me.sTargetClass, var theMap = {
iInputId: me.id, sTargetClass: me.sTargetClass,
sAttCode: me.sAttCode, iInputId: me.id,
'json': me.oWizardHelper.ToJSON() sAttCode: me.sAttCode,
}; 'json': me.oWizardHelper.ToJSON()
};
// Gather the values from the form // Gather the values from the form
// Gather the parameters from the search form // Gather the parameters from the search form
$('#'+sFormId+' :input').each( $('#'+sFormId+' :input').each(
function(i) function (i) {
{
if (this.name != '') if (this.name != '')
{ {
if ($(this).hasClass('htmlEditor')) if ($(this).hasClass('htmlEditor'))
@@ -540,15 +536,14 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
theMap['class'] = me.sClass; theMap['class'] = me.sClass;
$('#ac_create_'+me.id).dialog('close'); $('#ac_create_'+me.id).dialog('close');
// Make sure that we cancel any pending request before issuing another // Make sure that we cancel any pending request before issuing another
// since responses may arrive in arbitrary order // since responses may arrive in arbitrary order
me.StopPendingRequest(); me.StopPendingRequest();
// Run the query and get the result back directly in JSON // Run the query and get the result back directly in JSON
me.ajax_request = $.post( AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap, me.ajax_request = $.post(AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap,
function(data) function (data) {
{
$('#fstatus_'+me.id).html(''); $('#fstatus_'+me.id).html('');
if (data.id == 0) if (data.id == 0)
{ {
@@ -585,9 +580,8 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
} }
return false; // do NOT submit the form return false; // do NOT submit the form
}; };
this.Update = function() this.Update = function () {
{
if ($('#'+me.id).prop('disabled')) if ($('#'+me.id).prop('disabled'))
{ {
$('#v_'+me.id).html(''); $('#v_'+me.id).html('');
@@ -606,17 +600,17 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
$('#mini_search_'+me.id).show(); $('#mini_search_'+me.id).show();
} }
}; };
this.HKDisplay = function() this.HKDisplay = function () {
{ var theMap = {
var theMap = { sTargetClass: me.sTargetClass, sTargetClass: me.sTargetClass,
sInputId: me.id, sInputId: me.id,
sFilter: me.sFilter, sFilter: me.sFilter,
bSearchMode: me.bSearchMode, bSearchMode: me.bSearchMode,
sAttCode: me.sAttCode, sAttCode: me.sAttCode,
value: $('#'+me.id).val() value: $('#'+me.id).val()
}; };
if (me.bSelectMode) if (me.bSelectMode)
{ {
$('#fstatus_'+me.id).html('<img src="../images/indicator.gif" />'); $('#fstatus_'+me.id).html('<img src="../images/indicator.gif" />');
@@ -635,18 +629,17 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
me.oWizardHelper.UpdateWizard(); me.oWizardHelper.UpdateWizard();
theMap['json'] = me.oWizardHelper.ToJSON(); theMap['json'] = me.oWizardHelper.ToJSON();
} }
theMap['sRemoteClass'] = me.sTargetClass; theMap['sRemoteClass'] = me.sTargetClass;
theMap.operation = 'displayHierarchy'; theMap.operation = 'displayHierarchy';
// Make sure that we cancel any pending request before issuing another // Make sure that we cancel any pending request before issuing another
// since responses may arrive in arbitrary order // since responses may arrive in arbitrary order
me.StopPendingRequest(); me.StopPendingRequest();
// Run the query and display the results // Run the query and display the results
me.ajax_request = $.post( AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap, me.ajax_request = $.post(AddAppContext(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php'), theMap,
function(data) function (data) {
{
$('#ac_tree_'+me.id).html(data); $('#ac_tree_'+me.id).html(data);
var maxHeight = $(window).height()-110; var maxHeight = $(window).height()-110;
$('#tree_'+me.id).css({maxHeight: maxHeight}); $('#tree_'+me.id).css({maxHeight: maxHeight});
@@ -655,25 +648,23 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
); );
}; };
this.OnHKResize = function(event, ui) this.OnHKResize = function (event, ui) {
{ var dh = ui.size.height-ui.originalSize.height;
var dh = ui.size.height - ui.originalSize.height;
if (dh != 0) if (dh != 0)
{ {
var dlg_content = $('#dlg_tree_'+me.id+' .wizContainer'); var dlg_content = $('#dlg_tree_'+me.id+' .wizContainer');
var h = dlg_content.height(); var h = dlg_content.height();
dlg_content.height(h + dh); dlg_content.height(h+dh);
var tree = $('#tree_'+me.id); var tree = $('#tree_'+me.id);
var h = tree.height(); var h = tree.height();
tree.height(h + dh - 1); tree.height(h+dh-1);
} }
}; };
this.OnHKClose = function() this.OnHKClose = function () {
{
if (me.bSelectMode) if (me.bSelectMode)
{ {
$('#fstatus_'+me.id).html(''); $('#fstatus_'+me.id).html('');
} }
else else
{ {
@@ -684,21 +675,21 @@ function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper
$('#dlg_tree_'+me.id).remove(); $('#dlg_tree_'+me.id).remove();
}; };
this.DoHKOk = function() this.DoHKOk = function () {
{
iObjectId = $('#tree_'+me.id+' input[name=selectObject]:checked').val(); iObjectId = $('#tree_'+me.id+' input[name=selectObject]:checked').val();
$('#dlg_tree_'+me.id).dialog('close'); $('#dlg_tree_'+me.id).dialog('close');
// Query the server again to get the display name of the selected object // Query the server again to get the display name of the selected object
var theMap = { sTargetClass: me.sTargetClass, var theMap = {
iInputId: me.id, sTargetClass: me.sTargetClass,
iObjectId: iObjectId, iInputId: me.id,
sAttCode: me.sAttCode, iObjectId: iObjectId,
bSearchMode: me.bSearchMode, sAttCode: me.sAttCode,
operation: 'getObjectName' bSearchMode: me.bSearchMode,
}; operation: 'getObjectName'
};
// Make sure that we cancel any pending request before issuing another // Make sure that we cancel any pending request before issuing another
// since responses may arrive in arbitrary order // since responses may arrive in arbitrary order
me.StopPendingRequest(); me.StopPendingRequest();

View File

@@ -371,26 +371,6 @@ function ValidateCKEditField(sFieldId, sPattern, bMandatory, sFormId, nullValue,
} }
} }
/*
function UpdateDependentFields(aFieldNames)
{
//console.log('UpdateDependentFields:');
//console.log(aFieldNames);
index = 0;
oWizardHelper.ResetQuery();
oWizardHelper.UpdateWizard();
while(index < aFieldNames.length )
{
sAttCode = aFieldNames[index];
sFieldId = oWizardHelper.GetFieldId(sAttCode);
$('#v_'+sFieldId).html('<img src="../images/indicator.gif" />');
oWizardHelper.RequestAllowedValues(sAttCode);
index++;
}
oWizardHelper.AjaxQueryServer();
}
*/
function ResetPwd(id) function ResetPwd(id)
{ {
// Reset the values of the password fields // Reset the values of the password fields

View File

@@ -1,23 +1,23 @@
// Copyright (C) 2010-2018 Combodo SARL /*
// * Copyright (C) 2010-2020 Combodo SARL
// This file is part of iTop. *
// * This file is part of iTop.
// iTop is free software; you can redistribute it and/or modify *
// it under the terms of the GNU Affero General Public License as published by * iTop is free software; you can redistribute it and/or modify
// the Free Software Foundation, either version 3 of the License, or * it under the terms of the GNU Affero General Public License as published by
// (at your option) any later version. * the Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// iTop is distributed in the hope that it will be useful, *
// but WITHOUT ANY WARRANTY; without even the implied warranty of * iTop is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * but WITHOUT ANY WARRANTY; without even the implied warranty of
// GNU Affero General Public License for more details. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License *
// along with iTop. If not, see <http://www.gnu.org/licenses/> * You should have received a copy of the GNU Affero General Public License
*/
// JavaScript Document
function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizHelper, sExtKeyToRemote, bDoSearch) function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizHelper, sExtKeyToRemote, bDoSearch) {
{
this.id = id; this.id = id;
this.iInputId = iInputId; this.iInputId = iInputId;
this.sClass = sClass; this.sClass = sClass;
@@ -26,35 +26,39 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
this.bDuplicates = bDuplicates; this.bDuplicates = bDuplicates;
this.oWizardHelper = oWizHelper; this.oWizardHelper = oWizHelper;
this.sExtKeyToRemote = sExtKeyToRemote; this.sExtKeyToRemote = sExtKeyToRemote;
this.iMaxAddedId = 0; this.iMaxAddedId = 0;
this.aAdded = []; this.aAdded = [];
this.aRemoved = []; this.aRemoved = [];
this.aModified = {}; this.aModified = {};
this.bDoSearch = bDoSearch; // false if the search is not launched this.bDoSearch = bDoSearch; // false if the search is not launched
var me = this; var me = this;
this.Init = function() this.Init = function () {
{
// make sure that the form is clean // make sure that the form is clean
$('#linkedset_'+this.id+' .selection').each( function() { this.checked = false; }); $('#linkedset_'+this.id+' .selection').each(function () {
this.checked = false;
});
$('#'+this.id+'_btnRemove').prop('disabled', true); $('#'+this.id+'_btnRemove').prop('disabled', true);
$('#linkedset_'+me.id).on('remove', function() { $('#linkedset_'+me.id).on('remove', function () {
// prevent having the dlg div twice // prevent having the dlg div twice
$('#dlg_'+me.id).remove(); $('#dlg_'+me.id).remove();
}); });
me.RegisterChange(); me.RegisterChange();
var oInput = $('#'+this.iInputId); var oInput = $('#'+this.iInputId);
oInput.bind('update_value', function() { $(this).val(me.GetUpdatedValue()); }); oInput.bind('update_value', function () {
oInput.closest('form').submit(function() { return me.OnFormSubmit(); }); $(this).val(me.GetUpdatedValue());
});
oInput.closest('form').submit(function () {
return me.OnFormSubmit();
});
}; };
this.RemoveSelected = function() this.RemoveSelected = function () {
{
var my_id = '#'+me.id; var my_id = '#'+me.id;
$('#linkedset_'+me.id+' .selection:checked').each(function() { $('#linkedset_'+me.id+' .selection:checked').each(function () {
$(my_id+'_row_'+this.value).remove(); $(my_id+'_row_'+this.value).remove();
var iLink = $(this).attr('data-link-id'); var iLink = $(this).attr('data-link-id');
if (iLink > 0) if (iLink > 0)
@@ -79,7 +83,7 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
$(my_id+'_btnRemove').prop('disabled', true); $(my_id+'_btnRemove').prop('disabled', true);
// Re-run the zebra plugin to properly highlight the remaining lines & and take into account the removed ones // Re-run the zebra plugin to properly highlight the remaining lines & and take into account the removed ones
$('#linkedset_'+this.id+' .listResults').trigger('update').trigger("applyWidgets"); $('#linkedset_'+this.id+' .listResults').trigger('update').trigger("applyWidgets");
if ($('#linkedset_'+this.id+' .selection').length == 0) if ($('#linkedset_'+this.id+' .selection').length == 0)
{ {
// All items were removed: add a dummy hidden input to make sure that the linkset will be updated (emptied) when posted // All items were removed: add a dummy hidden input to make sure that the linkset will be updated (emptied) when posted
@@ -87,8 +91,7 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
} }
}; };
this.OnSelectChange = function() this.OnSelectChange = function () {
{
var nbChecked = $('#linkedset_'+me.id+' .selection:checked').length; var nbChecked = $('#linkedset_'+me.id+' .selection:checked').length;
if (nbChecked > 0) if (nbChecked > 0)
{ {
@@ -99,20 +102,20 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
$('#'+me.id+'_btnRemove').prop('disabled', true); $('#'+me.id+'_btnRemove').prop('disabled', true);
} }
}; };
this.AddObjects = function() this.AddObjects = function () {
{
var me = this; var me = this;
$('#'+me.id+'_indicatorAdd').html('&nbsp;<img src="../images/indicator.gif"/>'); $('#'+me.id+'_indicatorAdd').html('&nbsp;<img src="../images/indicator.gif"/>');
me.oWizardHelper.UpdateWizard(); me.oWizardHelper.UpdateWizard();
var theMap = { sAttCode: me.sAttCode, var theMap = {
iInputId: me.iInputId, sAttCode: me.sAttCode,
sSuffix: me.sSuffix, iInputId: me.iInputId,
bDuplicates: me.bDuplicates, sSuffix: me.sSuffix,
'class' : me.sClass, bDuplicates: me.bDuplicates,
operation: 'addObjects', 'class': me.sClass,
json: me.oWizardHelper.ToJSON() operation: 'addObjects',
}; json: me.oWizardHelper.ToJSON()
};
// Gather the already linked target objects // Gather the already linked target objects
theMap.aAlreadyLinked = []; theMap.aAlreadyLinked = [];
@@ -127,8 +130,7 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
"data": theMap, "data": theMap,
"dataType": "html" "dataType": "html"
}) })
.done(function (data) .done(function (data) {
{
$('#dlg_'+me.id).html(data); $('#dlg_'+me.id).html(data);
$('#dlg_'+me.id).dialog('open'); $('#dlg_'+me.id).dialog('open');
me.UpdateSizes(null, null); me.UpdateSizes(null, null);
@@ -147,9 +149,8 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
}) })
; ;
}; };
this.SearchObjectsToAdd = function() this.SearchObjectsToAdd = function () {
{
$('#count_'+me.id).change(function () { $('#count_'+me.id).change(function () {
var c = this.value; var c = this.value;
me.UpdateButtons(c); me.UpdateButtons(c);
@@ -161,8 +162,7 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
return false; // Don't submit the form, stay in the current page ! return false; // Don't submit the form, stay in the current page !
}; };
this.UpdateButtons = function(iCount) this.UpdateButtons = function (iCount) {
{
var okBtn = $('#btn_ok_'+me.id); var okBtn = $('#btn_ok_'+me.id);
if (iCount > 0) if (iCount > 0)
{ {
@@ -173,16 +173,16 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
okBtn.prop('disabled', true); okBtn.prop('disabled', true);
} }
}; };
this.DoAddObjects = function() this.DoAddObjects = function () {
{ var theMap = {
var theMap = { sAttCode: me.sAttCode, sAttCode: me.sAttCode,
iInputId: me.iInputId, iInputId: me.iInputId,
sSuffix: me.sSuffix, sSuffix: me.sSuffix,
bDuplicates: me.bDuplicates, bDuplicates: me.bDuplicates,
'class': me.sClass 'class': me.sClass
}; };
// Gather the parameters from the search form // Gather the parameters from the search form
var context = $('#SearchResultsToAdd_'+me.id); var context = $('#SearchResultsToAdd_'+me.id);
var selectionMode = $(':input[name=selectionMode]', context); var selectionMode = $(':input[name=selectionMode]', context);
@@ -192,14 +192,13 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
var sMode = selectionMode.val(); var sMode = selectionMode.val();
theMap['selectionMode'] = sMode; theMap['selectionMode'] = sMode;
$('#fs_SearchFormToAdd_'+me.id+' :input').each( $('#fs_SearchFormToAdd_'+me.id+' :input').each(
function(i) function (i) {
{ theMap[this.name] = this.value;
theMap[this.name] = this.value; }
} );
);
theMap['sRemoteClass'] = theMap['class']; // swap 'class' (defined in the form) and 'remoteClass' theMap['sRemoteClass'] = theMap['class']; // swap 'class' (defined in the form) and 'remoteClass'
theMap['class'] = me.sClass; theMap['class'] = me.sClass;
$(' :input[name^=storedSelection]', context).each(function() { $(' :input[name^=storedSelection]', context).each(function () {
if (theMap[this.name] == undefined) if (theMap[this.name] == undefined)
{ {
theMap[this.name] = []; theMap[this.name] = [];
@@ -214,34 +213,33 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
} }
// else // else
// { // {
// Normal table, retrieve all the checked check-boxes // Normal table, retrieve all the checked check-boxes
$(':checked[name^=selectObject]', context).each( $(':checked[name^=selectObject]', context).each(
function(i) function (i) {
if ((this.name != '') && ((this.type != 'checkbox') || (this.checked)))
{ {
if ( (this.name != '') && ((this.type != 'checkbox') || (this.checked)) ) arrayExpr = /\[\]$/;
if (arrayExpr.test(this.name))
{ {
arrayExpr = /\[\]$/; // Array
if (arrayExpr.test(this.name)) if (theMap[this.name] == undefined)
{ {
// Array theMap[this.name] = [];
if (theMap[this.name] == undefined)
{
theMap[this.name] = [];
}
theMap[this.name].push(this.value);
} }
else theMap[this.name].push(this.value);
{ }
theMap[this.name] = this.value; else
} {
theMap[this.name] = this.value;
} }
$(this).parents('tr:first').remove(); // Remove the whole line, so that, next time the dialog gets displayed it's no longer there
} }
); $(this).parents('tr:first').remove(); // Remove the whole line, so that, next time the dialog gets displayed it's no longer there
}
);
// } // }
theMap['operation'] = 'doAddObjects'; theMap['operation'] = 'doAddObjects';
theMap['max_added_id'] = this.iMaxAddedId; theMap['max_added_id'] = this.iMaxAddedId;
if (me.oWizardHelper == null) if (me.oWizardHelper == null)
{ {
theMap['json'] = ''; theMap['json'] = '';
@@ -254,9 +252,8 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
} }
$('#busy_'+me.iInputId).html('&nbsp;<img src="../images/indicator.gif"/>'); $('#busy_'+me.iInputId).html('&nbsp;<img src="../images/indicator.gif"/>');
// Run the query and display the results // Run the query and display the results
$.post( GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', theMap, $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', theMap,
function(data) function (data) {
{
if (data != '') if (data != '')
{ {
$('#'+me.id+'_empty_row').hide(); $('#'+me.id+'_empty_row').hide();
@@ -264,7 +261,9 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
$('#linkedset_'+me.id+' .listResults').trigger('update'); $('#linkedset_'+me.id+' .listResults').trigger('update');
$('#linkedset_'+me.id+' .listResults').tableHover(); $('#linkedset_'+me.id+' .listResults').tableHover();
$('#linkedset_'+me.id+' .listResults').trigger('update').trigger("applyWidgets"); // table is already sortable, just refresh it $('#linkedset_'+me.id+' .listResults').trigger('update').trigger("applyWidgets"); // table is already sortable, just refresh it
$('#linkedset_'+me.id+' :input').each( function() { $(this).trigger('validate', ''); }); // Validate newly added form fields... $('#linkedset_'+me.id+' :input').each(function () {
$(this).trigger('validate', '');
}); // Validate newly added form fields...
$('#busy_'+me.iInputId).html(''); $('#busy_'+me.iInputId).html('');
} }
}, },
@@ -274,63 +273,59 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
return false; return false;
}; };
this.AddLink = function (iAddedId, iRemote) this.AddLink = function (iAddedId, iRemote) {
{ // Assumption: this identifier will be higher than the previous one
// Assumption: this identifier will be higher than the previous one me.iMaxAddedId = iAddedId;
me.iMaxAddedId = iAddedId; var sFormPrefix = me.iInputId;
var sFormPrefix = me.iInputId; oAdded = {};
oAdded = {}; oAdded['formPrefix'] = sFormPrefix;
oAdded['formPrefix'] = sFormPrefix; oAdded['attr_'+sFormPrefix+this.sExtKeyToRemote] = iRemote;
oAdded['attr_' + sFormPrefix + this.sExtKeyToRemote] = iRemote; me.aAdded[iAddedId] = oAdded;
me.aAdded[iAddedId] = oAdded; };
};
this.OnLinkAdded = function(iAddedId, iRemote) this.OnLinkAdded = function (iAddedId, iRemote) {
{
this.AddLink(iAddedId, iRemote); this.AddLink(iAddedId, iRemote);
me.RegisterChange(); me.RegisterChange();
}; };
this.UpdateSizes = function(event, ui) this.UpdateSizes = function (event, ui) {
{
var dlg = $('#dlg_'+me.id); var dlg = $('#dlg_'+me.id);
var searchForm = $('#SearchFormToAdd_'+me.id); var searchForm = $('#SearchFormToAdd_'+me.id);
var results = $('#SearchResultsToAdd_'+me.id); var results = $('#SearchResultsToAdd_'+me.id);
var padding_right = 0; var padding_right = 0;
if (dlg.css('padding-right')) if (dlg.css('padding-right'))
{ {
padding_right = parseInt(dlg.css('padding-right').replace('px', '')); padding_right = parseInt(dlg.css('padding-right').replace('px', ''));
} }
var padding_left = 0; var padding_left = 0;
if (dlg.css('padding-left')) if (dlg.css('padding-left'))
{ {
padding_left = parseInt(dlg.css('padding-left').replace('px', '')); padding_left = parseInt(dlg.css('padding-left').replace('px', ''));
} }
var padding_top = 0; var padding_top = 0;
if (dlg.css('padding-top')) if (dlg.css('padding-top'))
{ {
padding_top = parseInt(dlg.css('padding-top').replace('px', '')); padding_top = parseInt(dlg.css('padding-top').replace('px', ''));
} }
var padding_bottom = 0; var padding_bottom = 0;
if (dlg.css('padding-bottom')) if (dlg.css('padding-bottom'))
{ {
padding_bottom = parseInt(dlg.css('padding-bottom').replace('px', '')); padding_bottom = parseInt(dlg.css('padding-bottom').replace('px', ''));
} }
width = dlg.innerWidth() - padding_right - padding_left - 22; // 5 (margin-left) + 5 (padding-left) + 5 (padding-right) + 5 (margin-right) + 2 for rounding ! width = dlg.innerWidth()-padding_right-padding_left-22; // 5 (margin-left) + 5 (padding-left) + 5 (padding-right) + 5 (margin-right) + 2 for rounding !
height = dlg.innerHeight() - padding_top - padding_bottom -22; height = dlg.innerHeight()-padding_top-padding_bottom-22;
wizard = dlg.find('.wizContainer:first'); wizard = dlg.find('.wizContainer:first');
wizard.width(width); wizard.width(width);
wizard.height(height); wizard.height(height);
form_height = searchForm.outerHeight(); form_height = searchForm.outerHeight();
results.height(height - form_height - 40); // Leave some space for the buttons results.height(height-form_height-40); // Leave some space for the buttons
}; };
this.GetUpdatedValue = function() this.GetUpdatedValue = function () {
{
var sSelector = '#linkedset_'+me.id+' :input[name^=attr_'+me.id+']'; var sSelector = '#linkedset_'+me.id+' :input[name^=attr_'+me.id+']';
var aIndexes = []; var aIndexes = [];
var aValues = []; var aValues = [];
$(sSelector).each(function() { $(sSelector).each(function () {
var re = /\[([^\[]+)\]\[(.+)\]/; var re = /\[([^\[]+)\]\[(.+)\]/;
var aMatches = []; var aMatches = [];
if (aMatches = this.name.match(re)) if (aMatches = this.name.match(re))
@@ -353,61 +348,69 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
} }
else else
{ {
aValues[index]['id'] = value; aValues[index]['id'] = value;
} }
} }
else else
{ {
aValues[index][aMatches[2]] = value; aValues[index][aMatches[2]] = value;
} }
} }
}); });
return JSON.stringify(aValues); return JSON.stringify(aValues);
}; };
this.RegisterChange = function() this.RegisterChange = function () {
{
// Listen only used inputs // Listen only used inputs
$('#linkedset_'+me.id+' :input[name^="attr_'+me.sAttCode+'["]').off('change').on('change', function() { $('#linkedset_'+me.id+' :input[name^="attr_'+me.sAttCode+'["]').off('change').on('change', function () {
if (!($(this).hasClass('selection'))) { if (!($(this).hasClass('selection')))
{
var oCheckbox = $(this).closest('tr').find('.selection'); var oCheckbox = $(this).closest('tr').find('.selection');
var iLink = oCheckbox.attr('data-link-id'); var iLink = oCheckbox.attr('data-link-id');
var iUniqueId = oCheckbox.attr('data-unique-id'); var iUniqueId = oCheckbox.attr('data-unique-id');
var sAttCode = $(this).closest('.attribute-edit').attr('data-attcode'); var sAttCode = $(this).closest('.attribute-edit').attr('data-attcode');
var value = $(this).val(); var value = $(this).val();
return me.OnValueChange(iLink, iUniqueId, sAttCode, value); return me.OnValueChange(iLink, iUniqueId, sAttCode, value, this);
} }
return true; return true;
}); });
}; };
this.OnValueChange = function(iLink, iUniqueId, sAttCode, value) /**
{ * @param int iLink id contained in the data-link-id attribute of the .selection widget
* @param int iUniqueId id contained in the data-unique-id attribute of the .selection widget
* @param string sAttCode
* @param string value new value of the autocomplete
* @param jQuery $oSourceObject object which fires the event
*/
this.OnValueChange = function (iLink, iUniqueId, sAttCode, value, $oSourceObject) {
var sFormPrefix = me.iInputId; var sFormPrefix = me.iInputId;
if (iLink > 0) { if (iLink > 0)
// Modifying an existing link {
var oModified = me.aModified[iLink]; // Modifying an existing link
if (oModified == undefined) { var oModified = me.aModified[iLink];
// Still not marked as modified if (oModified == undefined)
oModified = {}; {
oModified['formPrefix'] = sFormPrefix; // Still not marked as modified
} oModified = {};
// Weird formatting, aligned with the output of the direct links widget (new links to be created) oModified['formPrefix'] = sFormPrefix;
oModified['attr_' + sFormPrefix + sAttCode] = value; }
me.aModified[iLink] = oModified; // Weird formatting, aligned with the output of the direct links widget (new links to be created)
} oModified['attr_'+sFormPrefix+sAttCode] = value;
else { me.aModified[iLink] = oModified;
// Modifying a newly added link - the structure should already be up to date }
else
{
// Modifying a newly added link - the structure should already be up to date
if (iUniqueId < 0) if (iUniqueId < 0)
{ {
iUniqueId = -iUniqueId; iUniqueId = -iUniqueId;
} }
me.aAdded[iUniqueId]['attr_' + sFormPrefix + sAttCode] = value; me.aAdded[iUniqueId]['attr_'+sFormPrefix+sAttCode] = value;
} }
}; };
this.OnFormSubmit = function() this.OnFormSubmit = function () {
{
var oDiv = $('#linkedset_'+me.id); var oDiv = $('#linkedset_'+me.id);
var sToBeDeleted = JSON.stringify(me.aRemoved); var sToBeDeleted = JSON.stringify(me.aRemoved);
@@ -418,7 +421,7 @@ function LinksWidget(id, sClass, sAttCode, iInputId, sSuffix, bDuplicates, oWizH
$('<input type="hidden" name="attr_'+me.sAttCode+'_tbm">').val(sToBeModified).appendTo(oDiv); $('<input type="hidden" name="attr_'+me.sAttCode+'_tbm">').val(sToBeModified).appendTo(oDiv);
var aToBeCreated = []; var aToBeCreated = [];
me.aAdded.forEach(function(oAdded){ me.aAdded.forEach(function (oAdded) {
if (oAdded != null) if (oAdded != null)
{ {
aToBeCreated.push(oAdded); aToBeCreated.push(oAdded);

View File

@@ -1,125 +1,137 @@
// Copyright (C) 2010-2016 Combodo SARL /*
// * Copyright (C) 2010-2020 Combodo SARL
// This file is part of iTop. *
// * This file is part of iTop.
// iTop is free software; you can redistribute it and/or modify *
// it under the terms of the GNU Affero General Public License as published by * iTop is free software; you can redistribute it and/or modify
// the Free Software Foundation, either version 3 of the License, or * it under the terms of the GNU Affero General Public License as published by
// (at your option) any later version. * the Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// iTop is distributed in the hope that it will be useful, *
// but WITHOUT ANY WARRANTY; without even the implied warranty of * iTop is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * but WITHOUT ANY WARRANTY; without even the implied warranty of
// GNU Affero General Public License for more details. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License *
// along with iTop. If not, see <http://www.gnu.org/licenses/> * You should have received a copy of the GNU Affero General Public License
*/
// Wizard Helper JavaScript class to communicate with the WizardHelper PHP class /**
* Helper to handle dependant fields to be refreshed when parent field is updated.
if (!Array.prototype.indexOf) // Emulation of the indexOf function for IE and old browsers * The JS WizardHelper class has a WizardHelper PHP counterpart.
{ *
Array.prototype.indexOf = function(elt /*, from*/) * How to use it :
{ *
var len = this.length; * 1) Initialize by calling :
var from = Number(arguments[1]) || 0; * <pre><code>
from = (from < 0) ? Math.ceil(from) : Math.floor(from); * var oWizardHelper = new WizardHelper('Team', '', '');
* oWizardHelper.SetFieldsMap({"name":"2_name","status":"2_status","org_id":"2_org_id","email":"2_email","phone":"2_phone","notify":"2_notify","function":"2_function","id":"_id","persons_list":"2_persons_list","tickets_list":"2_tickets_list","cis_list":"2_cis_list"});
if (from < 0) from += len; oWizardHelper.SetFieldsCount(11);
for (; from < len; from++) * </code></pre>
{ *
if (from in this && this[from] === elt) return from; * 2) On field update launch the UpdateField method, passing the fields to update. This list is retrieved using
} * \MetaModel::GetDependentAttributes.
return -1; * For now this is launched by an handler on the 'change.dependencies' event, and this event is fired by each field (see
* \cmdbAbstractObject::GetFormElementForField and $aEventsList var)
* <pre><code>
* $('#2_name')
* .unbind('change.dependencies')
* .bind('change.dependencies', function(evt, sFormId) {
* return oWizardHelper.UpdateDependentFields(['friendlyname']);
* }
* );
* </code></pre>
*
* 3) The WizardHelper JS object will send an XHR query to ajax.render.php with operation=wizard_helper
* A new WizardHelper PHP object will be initialized with \WizardHelper::FromJSON
* This will send back to the browser fields updates, by returning JS code that will :
*
* * update JS WizardHelper m_oData attribute
* * launch JS WizardHelper UpdateFields() method
*
* @param sClass
* @param sFormPrefix
* @param sState
* @param sInitialState
* @param sStimulus
* @constructor
*/
function WizardHelper(sClass, sFormPrefix, sState, sInitialState, sStimulus) {
this.m_oData = {
'm_sClass': '',
'm_oFieldsMap': {},
'm_oCurrentValues': {},
'm_aDefaultValueRequested': [],
'm_aAllowedValuesRequested': [],
'm_oDefaultValue': {},
'm_oAllowedValues': {},
'm_iFieldsCount': 0,
'm_sFormPrefix': sFormPrefix,
'm_sState': sState
}; };
}
function WizardHelper(sClass, sFormPrefix, sState, sInitialState, sStimulus)
{
this.m_oData = { 'm_sClass' : '',
'm_oFieldsMap': {},
'm_oCurrentValues': {},
'm_aDefaultValueRequested': [],
'm_aAllowedValuesRequested': [],
'm_oDefaultValue': {},
'm_oAllowedValues': {},
'm_iFieldsCount' : 0,
'm_sFormPrefix' : sFormPrefix,
'm_sState': sState
};
this.m_oData.m_sClass = sClass; this.m_oData.m_sClass = sClass;
// Setting optional transition data // Setting optional transition data
if(sInitialState !== undefined) if (sInitialState !== undefined)
{ {
this.m_oData.m_sInitialState = sInitialState; this.m_oData.m_sInitialState = sInitialState;
} }
if(sStimulus !== undefined) if (sStimulus !== undefined)
{ {
this.m_oData.m_sStimulus = sStimulus; this.m_oData.m_sStimulus = sStimulus;
} }
// Methods // Methods
this.SetFieldsMap = function (oFieldsMap) this.SetFieldsMap = function (oFieldsMap) {
{
this.m_oData.m_oFieldsMap = oFieldsMap; this.m_oData.m_oFieldsMap = oFieldsMap;
}; };
this.SetFieldsCount = function (count) this.SetFieldsCount = function (count) {
{
this.m_oData.m_iFieldsCount = count; this.m_oData.m_iFieldsCount = count;
}; };
this.GetFieldId = function(sFieldName) this.GetFieldId = function (sFieldName) {
{
id = this.m_oData.m_oFieldsMap[sFieldName]; id = this.m_oData.m_oFieldsMap[sFieldName];
return id; return id;
}; };
this.RequestDefaultValue = function (sFieldName) this.RequestDefaultValue = function (sFieldName) {
{
currentValue = this.UpdateCurrentValue(sFieldName); currentValue = this.UpdateCurrentValue(sFieldName);
if (currentValue == null) if (currentValue == null)
{ {
this.m_oData.m_aDefaultValueRequested.push(sFieldName); this.m_oData.m_aDefaultValueRequested.push(sFieldName);
} }
}; };
this.RequestAllowedValues = function (sFieldName) this.RequestAllowedValues = function (sFieldName) {
{
this.m_oData.m_aAllowedValuesRequested.push(sFieldName); this.m_oData.m_aAllowedValuesRequested.push(sFieldName);
}; };
this.SetCurrentValue = function (sFieldName, currentValue) this.SetCurrentValue = function (sFieldName, currentValue) {
{
this.m_oData.m_oCurrentValues[sFieldName] = currentValue; this.m_oData.m_oCurrentValues[sFieldName] = currentValue;
}; };
this.ToJSON = function () this.ToJSON = function () {
{
return JSON.stringify(this.m_oData); return JSON.stringify(this.m_oData);
}; };
this.FromJSON = function (sJSON) this.FromJSON = function (sJSON) {
{
//console.log('Parsing JSON:'+sJSON); //console.log('Parsing JSON:'+sJSON);
this.m_oData = JSON.parse(sJSON); this.m_oData = JSON.parse(sJSON);
}; };
this.ResetQuery = function () this.ResetQuery = function () {
{
this.m_oData.m_aDefaultValueRequested = []; this.m_oData.m_aDefaultValueRequested = [];
this.m_oData.m_oDefaultValue = {}; this.m_oData.m_oDefaultValue = {};
this.m_oData.m_aAllowedValuesRequested = []; this.m_oData.m_aAllowedValuesRequested = [];
this.m_oData.m_oAllowedValues = {}; this.m_oData.m_oAllowedValues = {};
}; };
this.UpdateFields = function () this.UpdateFields = function () {
{
var aRefreshed = []; var aRefreshed = [];
//console.log('** UpdateFields **'); //console.log('** UpdateFields **');
// Set the full HTML for the input field // Set the full HTML for the input field
for(i=0; i<this.m_oData.m_aAllowedValuesRequested.length; i++) for (i = 0; i < this.m_oData.m_aAllowedValuesRequested.length; i++)
{ {
var sAttCode = this.m_oData.m_aAllowedValuesRequested[i]; var sAttCode = this.m_oData.m_aAllowedValuesRequested[i];
var sFieldId = this.m_oData.m_oFieldsMap[sAttCode]; var sFieldId = this.m_oData.m_oFieldsMap[sAttCode];
@@ -138,7 +150,7 @@ function WizardHelper(sClass, sFormPrefix, sState, sInitialState, sStimulus)
{ {
sAttCode = this.m_oData.m_aDefaultValueRequested[i]; sAttCode = this.m_oData.m_aDefaultValueRequested[i];
defaultValue = this.m_oData.m_oDefaultValue[sAttCode]; defaultValue = this.m_oData.m_oDefaultValue[sAttCode];
sFieldId = this.m_oData.m_oFieldsMap[sAttCode]; sFieldId = this.m_oData.m_oFieldsMap[sAttCode];
$('#'+sFieldId).val(defaultValue); $('#'+sFieldId).val(defaultValue);
if (!aRefreshed.indexOf(sFieldId)) if (!aRefreshed.indexOf(sFieldId))
{ {
@@ -146,15 +158,14 @@ function WizardHelper(sClass, sFormPrefix, sState, sInitialState, sStimulus)
} }
} }
// For each "refreshed" field, asynchronously trigger a change in case there are dependent fields to update // For each "refreshed" field, asynchronously trigger a change in case there are dependent fields to update
for(i=0; i<aRefreshed.length; i++) for (i = 0; i < aRefreshed.length; i++)
{ {
var sString = "$('#"+aRefreshed[i]+"').trigger('change').trigger('update');"; var sString = "$('#"+aRefreshed[i]+"').trigger('change').trigger('update');";
window.setTimeout(sString, 1); // Synchronous 'trigger' does nothing, call it asynchronously window.setTimeout(sString, 1); // Synchronous 'trigger' does nothing, call it asynchronously
} }
}; };
this.UpdateWizard = function () this.UpdateWizard = function () {
{
//console.log('** UpdateWizard **') //console.log('** UpdateWizard **')
for(sFieldCode in this.m_oData.m_oFieldsMap) for(sFieldCode in this.m_oData.m_oFieldsMap)
{ {
@@ -163,38 +174,31 @@ function WizardHelper(sClass, sFormPrefix, sState, sInitialState, sStimulus)
this.UpdateCurrentValue(sCleanFieldCode); this.UpdateCurrentValue(sCleanFieldCode);
} }
}; };
this.UpdateWizardToJSON = function () this.UpdateWizardToJSON = function () {
{
this.UpdateWizard(); this.UpdateWizard();
return this.ToJSON(); return this.ToJSON();
}; };
this.AjaxQueryServer = function () this.AjaxQueryServer = function () {
{
//console.log('data sent:', this.ToJSON()); //console.log('data sent:', this.ToJSON());
//console.log('oWizard:', this); //console.log('oWizard:', this);
$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php',
{ operation: 'wizard_helper', json_obj: this.ToJSON() }, {operation: 'wizard_helper', json_obj: this.ToJSON()},
function(html){ function (html) {
$('#ajax_content').html(html); $('#ajax_content').html(html);
$('.blockUI').parent().unblock(); $('.blockUI').parent().unblock();
//console.log('data received:', oWizardHelper); }
//oWizardHelper.FromJSON(json_data); );
//oWizardHelper.UpdateFields(); // Is done directly in the html provided by ajax.render.php
//console.log(oWizardHelper);
//$('#wizStep'+ G_iCurrentStep).unblock( {fadeOut: 0} );
});
}; };
this.Preview = function (divId) this.Preview = function (divId) {
{
//console.log('data sent:', this.ToJSON()); //console.log('data sent:', this.ToJSON());
//console.log('oWizard:', this); //console.log('oWizard:', this);
$('#'+divId).load(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?operation=wizard_helper_preview', $('#'+divId).load(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?operation=wizard_helper_preview',
{'json_obj': this.ToJSON()}, {'json_obj': this.ToJSON()},
function(responseText, textStatus, XMLHttpRequest){ function (responseText, textStatus, XMLHttpRequest) {
$('#wizStep'+ G_iCurrentStep).unblock( {fadeOut: 0} ); $('#wizStep'+G_iCurrentStep).unblock({fadeOut: 0});
}); });
}; };
@@ -210,18 +214,23 @@ function WizardHelper(sClass, sFormPrefix, sState, sInitialState, sStimulus)
return value; return value;
}; };
this.UpdateDependentFields = function(aFieldNames) this.UpdateDependentFields = function (aFieldNames) {
{ var index = 0,
index = 0; nbOfFieldsToUpdate = 0,
sAttCode,
sFieldId;
this.ResetQuery(); this.ResetQuery();
this.UpdateWizard(); this.UpdateWizard();
while(index < aFieldNames.length ) while (index < aFieldNames.length)
{ {
sAttCode = aFieldNames[index]; sAttCode = aFieldNames[index];
sFieldId = this.GetFieldId(sAttCode); sFieldId = this.GetFieldId(sAttCode);
if (sFieldId !== undefined) { if (sFieldId !== undefined)
$('#fstatus_' + sFieldId).html('<img src="../images/indicator.gif" />'); {
$('#field_' + sFieldId).find('div').block({ nbOfFieldsToUpdate++;
$('#fstatus_'+sFieldId).html('<img src="../images/indicator.gif" />');
$('#field_'+sFieldId).find('div').block({
message: '', message: '',
overlayCSS: {backgroundColor: '#f1f1f1', opacity: 0.3} overlayCSS: {backgroundColor: '#f1f1f1', opacity: 0.3}
}); });
@@ -229,33 +238,35 @@ function WizardHelper(sClass, sFormPrefix, sState, sInitialState, sStimulus)
} }
index++; index++;
} }
this.AjaxQueryServer();
if (nbOfFieldsToUpdate > 0)
{
this.AjaxQueryServer();
}
}; };
this.ReloadObjectCreationForm = function(sFormId, sTargetState) this.ReloadObjectCreationForm = function (sFormId, sTargetState) {
{
$('#'+sFormId).block(); $('#'+sFormId).block();
this.UpdateWizard(); this.UpdateWizard();
this.ResetQuery(); this.ResetQuery();
var sTransactionId = $('input[name=transaction_id]').val(); var sTransactionId = $('input[name=transaction_id]').val();
$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php',
{ json_obj: this.ToJSON(), operation: 'obj_creation_form', target_state: sTargetState, transaction_id: sTransactionId }, {json_obj: this.ToJSON(), operation: 'obj_creation_form', target_state: sTargetState, transaction_id: sTransactionId},
function(data) function (data) {
{
// Delete any previous instances of CKEditor // Delete any previous instances of CKEditor
$('#'+sFormId).find('.htmlEditor').each(function() { $('#'+sFormId).find('.htmlEditor').each(function () {
var sId = $(this).attr('id'); var sId = $(this).attr('id');
var editorInst = CKEDITOR.instances[sId]; var editorInst = CKEDITOR.instances[sId];
if (editorInst.status == 'ready') if (editorInst.status == 'ready')
{ {
editorInst.destroy(true); editorInst.destroy(true);
} }
}); });
$('#'+sFormId).html(data); $('#'+sFormId).html(data);
onDelayedReady(); onDelayedReady();
$('#'+sFormId).unblock(); $('#'+sFormId).unblock();
} }
); );
}; };
} }

View File

@@ -701,6 +701,7 @@ try
break; break;
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
/// WizardHelper : see the corresponding PHP class, and JS class
case 'wizard_helper_preview': case 'wizard_helper_preview':
$oPage->SetContentType('text/html'); $oPage->SetContentType('text/html');