How can i use presave function to prevent a model from saving if there any change had been done

8 views (last 30 days)
I have a simulink model, and wanted to add some code which will prevent me/someone from saving it after making any change (Change means version of the model or something). I hope this can be handled by presave function

Accepted Answer

Anushka
Anushka on 19 Feb 2025
As you have correctly mentioned, you can use Simulink's 'PreSaveFcn' callback to prevent saving a model after changes. The 'PreSaveFcn' executes before the model is saved, so you can use it to chcek if modifications have been made and then prevent saving.
You can follow the below given steps to implement:
  1. Open your Simulink model.
  2. Go to Model properties > Callback > PreSaveFcn.
  3. Add the following MATLAB code in the 'PreSaveFcn' callback:
modelName=bdroot;
modelFile=which(modelName);
if strcmp(get_param(modelName,'Dirty'),'on')
errordlg('Saving is disabled for this model after changes.Revert changes to save.','Save Disabled');
error('Saving is disabled for this model after modification.');
end
This will throw an error saying "Saving is disabled for this model after modification.".
To prevent saving model when the version changes, you can store the initial version in the model's UserData or Model Workspace and check it in the 'PreSaveFcn' callback:
  1. Open the Simulink model.
  2. Set an initial version number using the 'set_param' function:
% This stores version 1.0 in the model's workspace.
modelName=bdroot;
hws=get_param(modelName,'ModelWorkspace');
assignin(hws,'StoredVersion','1.0');
3. Open Model Properties > Callbacks > PreSaveFcn.
4. Add the following MATLAB code:
modelName=bdroot;
userData=get_param(modelName,'ModelWorkspace');
if evalin(hws,'exist(''StoredVersion'',''var'')')
storedVersion=evalin(hws,'StoredVersion');
else
storedVersion='Unknown';
end
currentVersion=get_param(modelName,'ModelVersion');
if ~strcmp(storedVersion,currentVersion)
errordlg(sprintf('Saving is disabled because the model version changed.\nStored Version: %s\nCurrent Version: %s', ...
storedVersion,currentVersion),'Save Disabled');
error('Saving is disabled due to version change.');
end
This will throw an error saying "Saving is disabled due to version change.".
Hope this helps!

More Answers (0)

Categories

Find more on Simulink in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!