Resco JavaScript Bridge: Difference between revisions

Jump to navigation Jump to search
Line 863: Line 863:
</div></syntaxhighlight>
</div></syntaxhighlight>


== EntityList ==


References to objects and methods that we work with:


* EntityList <br>https://www.resco.net/javascript-bridge-reference/#MobileCRM_UI_EntityList
* Handle EntityList change event<br> https://www.resco.net/javascript-bridge-reference/#MobileCRM_UI_EntityList_onChange
* Request EntityList object<br> https://www.resco.net/javascript-bridge-reference/#MobileCRM_UI_EntityList_requestObject


=== Create a view with iframe for EntityList in Woodford ===


At the beginning of working with the entity list object, we have to create and bind an iframe to an existing or a new view. In our example, we create a new view on the Account entity.


# Edit an [[app projects|app project]] in [[Woodford]].
# On the '''Project''' menu, select '''Account''', then click '''Show UI'''.
# Click '''New View''' and create an empty view:<br>[[File:New iframe view.png|600px]]
# Click '''iFrame''' and add an HTML file to the view:<br>[[File:Add iframe to view.png|600px]]
What does the parameter '''Provides data source''' mean?
* Check it if you want that your HTML retrieves a fetch with entity result to be displayed in the view.
* Clear it to use the original data source defined in the view. You will not be able to change it using a fetch.
: In both cases, the script is properly attached if the URL address is correct. It is good to know that all methods work except those that set the data source.
=== Using EntityList object and its methods ===
In this example, we discuss and explain scenarios that can help you understand the logic and use of the mentioned objects. We already know how to add iframes to views. Let's assume that we have a script bound to the Account entity view.
==== Retrieve fetch data source and create view ====
Our first scenario loads data by using the fetch method and sets an additional filter for the retrieved data. We use only the basic functions included in every fetch. This is the easiest way to modify your entity list source.
The code from reference page:
https://www.resco.net/javascript-bridge-reference/#MobileCRM_UI_EntityList_setDataSource
In the first example, we can see that we can modify the fetch source by adding a filter or basic fetch methods. All these inputs create an array result that represents our source. All element data in the array are displayed in a single row. For a better explanation, let’s see how it looks in the app.
[[File:JSBridge Guide 021.png|600px]]
From the screenshot, it is obvious that the values of the correct fields are displayed. In the code from the reference page, we want the fetch output as an array of dynamic entities. This object carries the values of the entity property.
{{Note|It is very important to make sure that all the properties which we filter or display are enabled and we display only those which are bound on the row.}}
=== Commands ===
Entity views contain entity lists that are represented by rows. Each row can contain one or more row commands (buttons). Next command which we call primary command is part of view, as well the multi-selection command. Commands are created in Woodford, except primary command. This one is created in the background of the code. The entity list also allows the same command handling as on the EntityForm.
* List Buttons – Each row in the list contains this button. In our scenario, we create a custom command that takes a photo attachment annotation for the currently selected entity.
Woodford setup:
# Edit a [[view]] in Woodford.
# Click '''Buttons''', then '''New Command'''.
# As '''Name''' enter ''createNotePhoto''.
# As '''Label''' enter ''Photo''.
# Click '''OK'''.
Now we can insert the logic into an iframe that creates the annotation. This operation requires that the user has the permission to take a picture and code to use DocumentService object and access to files.
The most important part of the code and this section is to register a handler that listens for a specific command name. To run logic when the command is executed, we need to use callback. In this callback, we retrieve an entity list object with all properties and methods available. In a situation like this, we need to access the selected record from the list.
'''Code:'''
<syntaxhighlight lang='js'>
MobileCRM.UI.EntityList.onCommand("custom_createNotePhoto", function (entityList) {
   /// <param name='entityList' type='MobileCRM.UI.EntityList'/>
   /// selected record in list.
   var regarding = entityList.context.entities[0];
   var doc = new MCRMdocument();
   doc.capturePhoto(regarding);
}, true, null);
</syntaxhighlight>
The code above shows how to register the command handler and access the selected record. In the code, we can see another important thing: the entityList contains an array of context entities. In our case, we have selected only one record, since we work with the row button. On the other hand, we can access multiple records, which is achieved by selecting the use of multi-select option.
Next part of code is developed as an example, it requires understanding document service object.
'''DocumentService:'''
https://www.resco.net/javascript-bridge-reference/#MobileCRM_Services_DocumentService
The rest of the code, class of MCRMdocument:
<syntaxhighlight lang='js'>
var MCRMdocument = function () {
   this._service;
   construnctor:(this._service = new MobileCRM.Services.DocumentService());
   MCRMdocument.prototype.capturePhoto = function (regarding) {
      /// <param name='regrding' type='MobileCRM.Refernce'/>
      if (this._service != undefined) {
         this._service.capturePhoto(function (fileInfo) {
            this.getDocumentBody(regarding, fileInfo);
         }, MobileCRM.bridge.alert, null);
      }
   };
   MCRMdocument.prototype.selectPhoto = function (regarding) {
      /// <param name='regrding' type='MobileCRM.Refernce'/>
      if (this._service != undefined) {
         this._service.selectFile(function (fileInfo) {
            this.getDocumentBody(regarding, fileInfo);
         }, MobileCRM.bridge.alert, null);
      }
   };
   createAnnotation = function (regarding, fileInfo, documentBody) {
      /// <param name='regrding' type='MobileCRM.Refernce'/>
      /// <param name='fileInfo' type='MobileCRM.Settings._fileInfo'/>
      /// <param name='documentBody' type='base64'>File base 64 string.<param>
      var note = MobileCRM.DynamicEntity.createNew("annotation");
      if (fileInfo) {
         var splits = fileInfo.filePath.split("\\");
         note.properties.filename = splits[splits.length - 1];
         note.properties.mimetype = fileInfo.mimeType;
         note.properties.isdocument = 1;
         note.properties.documentbody = documentBody || " ";
      }
      note.properties.subject = "Document";
      note.properties.notetext = "Test attachment from document service";
      note.properties.objectid = regarding;
      note.save(function (err) {
         if (err) MobileCRM.bridge.alert(err);
         else {
            // display newly created annotation
            MobileCRM.UI.FormManager.showEditDialog(this.entityName, this.id);
         }
      });
   };
   getDocumentBody = function (regarding, fileInfo) {
      /// <param name='regrding' type='MobileCRM.Refernce'/>
      /// <param name='fileInfo' type='MobileCRM.Settings._fileInfo'/>
      MobileCRM.Application.readFileAsBase64(fileInfo.filePath, function (base64) {
         this.createAnnotation(regarding, fileInfo, base64);
      }, MobileCRM.bridge.alert);
   }
}
</syntaxhighlight>
Another example of the native command handler '''Call'''. The steps are the same as before, we just need to bind iframe on the Entity view and create handler for specific command with the exact name.
In the next example, we take the entity list context property of the currently selected record and display a message box with those properties. Once the user selects the option, we can make a call with the desired option.
'''Code:'''
<syntaxhighlight lang='js'>
var cmd = "Call";
   MobileCRM.UI.EntityList.onCommand(cmd, function (entityList) {
      /// <param name='entityList' type='MobileCRM.UI.EntityList'/>
      var msg = new MobileCRM.UI.MessageBox("Make a call?", "Cancel");
      var currentRec = entityList.context.entities[0];
      msg.items = [currentRec.fax, "some another option"]; // here you have to set your option of message box (buttons)
      msg.show(function (number) {
         MobileCRM.Platform.makeCall(number, MobileCRM.bridge.alert, null);
      }, MobileCRM.bridge.alert, null);
   }, true, null);
</syntaxhighlight>
How it looks in the app:
[[File:JSBridge Guide 023.png|600px]]
==== Primary command ====
This type of command overrides the primary entity list view command. It can be created only in the background of the code, from a script. Its handler is executed after this button is clicked.
Screenshot from the app:
[[File:JSBridge Guide 024.png]]
In our example, we just override the basic button with some additional options. It means that we create an entity record of the entity type, by using predefined fields values.
'''Code:'''
<syntaxhighlight lang='js'>
MobileCRM.UI.EntityList.setPrimaryCommand("Create", function (entityList) {
   /// <param name='entityList' type='MobileCRM.UI.EntityList'>
   MobileCRM.UI.FormManager.showNewDialog("account", null, {
      "@initialize": {
         telephone1: 555 666 777, // new contact will have this phone
            address1_line1: "Radmond 71", // ... and address too
            address1_city: "Los Angeles"
      }
   }, null);
   MobileCRM.bridge.alert("Test!");
}, null);
</syntaxhighlight>
==== Multi Select command ====
The command allows users to select more than one record. The entity list object contains a method that handles these commands. It is the same as the first example scenario. We need to use the onCommand method with a valid command name.
In our scenario, we iterate through the selected entities and compare them with the values of predefined entities. It is a very simple validation for multi-selection on entity list.
Woodford setup:
# Edit a [[view]] in Woodford.
# Click '''Multi Select''', then '''New Command'''.
# As '''Name''' enter ''multiselect''.
# As '''Label''' enter ''Selected''.
# Click '''OK'''.
'''Code:'''
<syntaxhighlight lang='js'>
MobileCRM.UI.EntityList.onCommand("custom_multiselec", function (entityList) {
   /// <param name='entityList' type='MobileCRM.UI.EntityList'>
   var predefinedNames = ["!Active Cycling", "Basic Bike Components"];
      var selectedEntities = entityList.context.entities;
      var exist = false;
      predefinedNames.forEach(function (val, i) {
         selectedEntities.forEach(function (sel, j) {
            if (sel == val) {
               exist = true;
               break;
            }
         });
      if (exist == false)
      MobileCRM.bridge.alert("Selected entity is not in predefined array.\n" + val.properties.name);
      });
   }, true, null);
},
</syntaxhighlight>
This was a sample scenario for how to work with commands on the entity list. These methods and functions allow users to manipulate the data and handle command execution. It is very useful to be able to implement your custom logic if it is required.
=== Event handlers on entity list ===
The entity list object contains events that can be explicitly called and handled by specific methods. Native Entity list allows users to edit fields, select them, call buttons, etc. In this section, we discuss how to control and use those options in sample scenarios.
Our sample scenario looks as follows: we have one field ''fax'' on our row and we want to handle when this field is changed to validate input.
Woodford setup: Make sure to set '''Kind''' to '''Text-Edit''' to make it editable.
[[File:View with fax validation.png|600px]]
Now we must register the '''onChange''' event handler to allow us to control what value the user writes to the fax field. In our case, we just check if the value is not empty. If yes, we explicitly set a default value.
<syntaxhighlight lang='js'>
MobileCRM.UI.EntityList.onChange(function (entityList) {
   /// <param name='entityList' type='MobileCRM.UI.EntityList'/>
   var context = entityList.context;
   if (context.propertyName == "fax") {
      var editedEntities = entityList.context.entities;
      var props = editedEntities[0].properties;
      if (!props.fax)
         props.fax = "554 321"; /// value by default.
   }
}, MobileCRM.bridge.alert, null);
</syntaxhighlight>
In the previous example, we only handle changes on entity list row, but if you know what row and property you need directly to edit or edit and save immediately, then check out the following method, which performs exactly this action.
Reference to the code:
https://www.resco.net/javascript-bridge-reference/#MobileCRM_UI_EntityList_setEntityProperty
In the next example, we follow a similar scenario as in the previous example, except for the onSave event handler and set ‘errorMessage’ property in case of validation fail. See this example and the code snippet on the reference page for more. The onSave handler works the same on entity form and another part of the application where this handler can be registered.
Reference to code:
https://www.resco.net/javascript-bridge-reference/#MobileCRM_UI_EntityList_onSave
==== Entity list click event ====
This part tells more about the click event and its context. Imagine that we want to handle clicking on the entity list, on any row or cell on it. This event needs to contain some property that describes entities, property name, and event definition.
* Entities – It represents the tapped dynamic entities. In the code, we use an array for definition, each element of it is any tapped entity.
* Property name – The field name that was clicked within the list item.
* Event – Definition for an event. EntityListClickEvent object describes what action has been done while specifying the cell, row and binding event value.
: Action that the event can describe can be found here: https://www.resco.net/javascript-bridge-reference/#MobileCRM_UI_EntityListCellAction.
This event can be used in many scenarios. In most cases, you just want to know what cell/row was selected and which entity fields were modified. For further detail, please visit our reference page.
== Global events ==
<syntaxhighlight lang='js'>
</syntaxhighlight>
<syntaxhighlight lang='js'>
</syntaxhighlight>
<syntaxhighlight lang='js'>
</syntaxhighlight>
<syntaxhighlight lang='js'>
</syntaxhighlight>
<syntaxhighlight lang='js'>
</syntaxhighlight>


<syntaxhighlight lang='js'>
<syntaxhighlight lang='js'>

Navigation menu