Get newly created id of a record before redirecting page - sugarcrm

I would like to retrieve the id of a newly created record using javascript when I click on save button and just before redirecting page.
Do you have any idea please ?
Thank you !

One way to do this in Sugar 7 would be by overriding the CreateView.
Here an example of a CustomCreateView that outputs the new id in an alert-message after a new Account was successfully created, but before Sugar gets to react to the created record.
custom/modules/Accounts/clients/base/views/create/create.js:
({
extendsFrom: 'CreateView',
// This initialize function override does nothing except log to console,
// so that you can see that your custom view has been loaded.
// You can remove this function entirely. Sugar will default to CreateView's initialize then.
initialize: function(options) {
this._super('initialize', [options]);
console.log('Custom create view initialized.');
},
// saveModel is the function used to save the new record, let's override it.
// Parameters 'success' and 'error' are functions/callbacks.
// (based on clients/base/views/create/create.js)
saveModel: function(success, error) {
// Let's inject our own code into the success callback.
var custom_success = function() {
// Execute our custom code and forward all callback arguments, in case you want to use them.
this.customCodeOnCreate(arguments)
// Execute the original callback (which will show the message and redirect etc.)
success(arguments);
};
// Make sure that the "this" variable will be set to _this_ view when our custom function is called via callback.
custom_success = _.bind(custom_success , this);
// Let's call the original saveModel with our custom callback.
this._super('saveModel', [custom_success, error]);
},
// our custom code
customCodeOnCreate: function() {
console.log('customCodeOnCreate() called with these arguments:', arguments);
// Retrieve the id of the model.
var new_id = this.model.get('id');
// do something with id
if (!_.isEmpty(new_id)) {
alert('new id: ' + new_id);
}
}
})
I tested this with the Accounts module of Sugar 7.7.2.1, but it should be possible to implement this for all other sidecar modules within Sugar.
However, this will not work for modules in backward-compatibility mode (those with #bwc in their URL).
Note: If the module in question already has its own Base<ModuleName>CreateView, you probably should extend from <ModuleName>CreateView (no Base) instead of from the default CreateView.
Be aware that this code has a small chance of breaking during Sugar upgrades, e.g. if the default CreateView code receives changes in the saveModel function definition.
Also, if you want to do some further reading on extending views, there is an SugarCRM dev blog post about this topic: https://developer.sugarcrm.com/2014/05/28/extending-view-javascript-in-sugarcrm-7/

I resolved this by using logic hook (after save), for your information, I am using Sugar 6.5 no matter the version of suitecrm.
Thank you !

Related

Kuzzle - inter-plugins communication (via method calls)

Is there a way with Kuzzle, to make two plugins communicate with each other?
Let's say a plugin A wants to call a method of a plugin B at boot time, or even runtime for some use cases. How can I do that ?
For now, there is no way to retrieve a particular plugin instance from another plugin. Plugins manager isn't reachable at plugin initialization, but in some way via a Kuzzle request (not the proper way of doing it)
function (request) {
const kSymbol = Object.getOwnPropertySymbols(request.context.user)[0];
request.context.user[kSymbol].pluginsManager.MyPlugin.someMethod(...args);
...
}
The idea behind this question would be to do something like this, when initializing the plugin
function init (customConfig, context) {
const { pluginsManager } = context;
const result = pluginsManager.MyPlugin.someMethod(...args);
// make something with the result ?
// For later use of plugins manager perhaps ?
this.context = context
}
Looks like Kuzzle Pipes would be the right thing to do it, cause they are synchronous and chainable, but pipes don't return anything when triggering an event
function init (customConfig, context) {
const result = context.accessors.trigger('someEvent', {
someAttribute: 'someValue'
});
console.log(result) // undefined
}
Thanks for your help !
full disclosure: I work for Kuzzle
Even if accessing the pluginManager like this may work at this time, we may change the internal implementation without warning since it's not documented so your plugin may not work in next version of Kuzzle.
The easiest way to use a feature from another plugin is exposing a new API method through a custom controller and then call it with the query method of the embedded SDK.
For example if your plugin name is notifier-plugin in the manifest:
this.controllers = {
email: {
send: request => { /* send email */ }
}
};
Then you can call it in another plugin like this:
await this.context.accessors.sdk.query({
controller: 'notifier-plugin/email',
action: 'send'
});
Please note that you can't make API calls in the plugin init method.
If you need to make API calls when Kuzzle start, then you can add a hook/pipe on the core:kuzzleStart event.
this.hooks = {
'core:kuzzleStart': () => this.context.accessors.sdk.query({
controller: 'notifier-plugin/email',
action: 'send'
});
};
Finally I noticed that you can't use pipes returns like in your example but I have proposed a feature to allow plugin developers to use the pipe chain return.
It will be available in the next version of Kuzzle.

Ext.define() order

I'm using Extjs5 and Sencha Cmd, and I'm working on a l10n engine (over gettext) to implement localization.
Suppose I want to offer a translation function to every class of my project, named _().
In every controller, view, model and any class, I'd like to be able to write something like that:
Ext.define('FooClass', {
someStrings: [
_('One string to translate'),
_('A second string to translate'),
_('Yet another string to translate')
]
});
First problem: _() must exist before all the Ext.define() of my project are executed. How to achieve that?
Second problem: _() is looking in "catalogs" that are some JavaScript files generated from .po files (gettext). So, those catalogs must have been loaded, before all the Ext.define() of my app are executed.
_() is a synchronous function, it musts immediately return the translated string.
Edit concerning the edited question
You have at least two ways to load External libraries:
Ext.Loader.loadScript
loadScript( options )
Loads the specified script URL and calls the supplied callbacks. If
this method is called before Ext.isReady, the script's load will delay
the transition to ready. This can be used to load arbitrary scripts
that may contain further Ext.require calls.
Parameters
options : Object/String/String[] //The options object or simply the URL(s) to load.
// options params:
url : String //The URL from which to load the script.
onLoad : Function (optional) //The callback to call on successful load.
onError : Function (optional) //The callback to call on failure to load.
scope : Object (optional) //The scope (this) for the supplied callbacks.
If you still run into problems you can force the loader to do a sync loading:
syncLoadScripts: function(options) {
var Loader = Ext.Loader,
syncwas = Loader.syncModeEnabled;
Loader.syncModeEnabled = true;
Loader.loadScripts(options);
Loader.syncModeEnabled = syncwas;
}
Place this in a file right after the ExtJS library and before the generated app.js.
Old Answer
You need to require a class when it is needed, that should solve your problems. If you don't require sencha command/the ExtJS class system cannot know that you need a specific class.
Ext.define('Class1', {
requires: ['Class2'],
items: [
{
xtype: 'combo',
fieldLabel: Class2.method('This is a field label')
}
]
});
For further reading take a look at:
requires
requires : String[]
List of classes that have to be loaded before instantiating this
class. For example:
Ext.define('Mother', {
requires: ['Child'],
giveBirth: function() {
// we can be sure that child class is available.
return new Child();
}
});
uses
uses : String[]
List of optional classes to load together with this class. These
aren't neccessarily loaded before this class is created, but are
guaranteed to be available before Ext.onReady listeners are invoked.
For example:
Ext.define('Mother', {
uses: ['Child'],
giveBirth: function() {
// This code might, or might not work:
// return new Child();
// Instead use Ext.create() to load the class at the spot if not loaded already:
return Ext.create('Child');
}
});
Define the translate function outside the scope of the ExtJs project and include it before the Ext application is included in the index.html.
The scripts are loaded in the right order and the _() function is ready to use in your whole project.
i18n.js
function _() {
// do the translation
}
index.html
<html>
<head>
<script src="i18n.js"></script>
<script id="microloader" type="text/javascript" src="bootstrap.js"></script>
</head>
<body>
</body>
</html>

Restangular extendModel on new object

Restangular offers a feature, extendModel, which lets you add functionality onto objects returned from the server. Is there any way to get these methods added to an empty / new model, that hasn't yet been saved to the server?
I wanted to do the same thing but didn't find an example. Here's how I ended up doing it:
models.factory('User', function(Restangular) {
var route = 'users';
var init = {a:1, b:2}; // custom User properties
Restangular.extendModel(route, function(model) {
// User functions
model.myfunc = function() {...}
return model;
});
var User = Restangular.all(route);
User.create = function(obj) {
// init provides default values which will be overridden by obj
return Restangular.restangularizeElement(null, _.merge({}, init, obj), route);
}
return User;
}
Some things to be aware of:
Use a function like _.merge() instead of angular.extend() because it clones the init variable rather than simply assigning its properties.
There is a known issue with Restangular 1.x that causes the Element's bound data to not be updated when you modify its properties (see #367 and related). The workaround is to call restangularizeElement() again before calling save(). However this call will always set fromServer to false which causes a POST to be sent so I wrote a wrapper function that checks if id is non-null and sets fromServer to true.

Getting value with javascript and use it in controller

First of all i am using play framework with scala,
What i have to do is , using the data which i am getting with that function;
onClick: function(node) {
if(!node) return;
alert(node.id);
var id = node.id;
}
So what the question is how i can call the methods from controller with this id ? Since js is client-side but scala works with server-side , i need something creative.
This is the function i need to call from my controller.
def supertrack(id:Long) = Action {
}
I have just found out that i need use ScalaJavaScriptRouting in order to send a ajax request to the server.
For the documentation
http://www.playframework.com/documentation/2.1.1/ScalaJavascriptRouting

Destroy server model does not update id to null

after I change to Backbone-Relational my model stopped to work when I call destroy().. I have to ensure that when it removes success on server there will be no more id at client side, so then when I try to save it again my model wont request PUT (update) - throws Record Not Found on server side.
Coffeescript side
save: ->
if isBlank #model.get("text")
#model.destroy() # after success it still with same attributes including id!!
else
#model.save()
Rails side
def destroy
#note = Note.find(params[:id])
#note.destroy
respond_with #note # callback is empty
end
Bug from Backbone-Relational perhaps? Does Backbone.js update id after destroy?
Backbone does not look like it modifies the Model on destruction in any way. Except removing it from its collection if any.
Check the code
What it does is triggering the event destroy so you easily can listen this event and do whatever you think is the proper behavior in destruction:
// code simplified and no tested
var MyModel = Backbone.Model.extend({
initialize: function(){
this.on( "destroy", this.afterDestroy, this );
},
afterDestroy: function(){
this.set( "id", null );
}
});