Up and running fast with Mendix (Part 2)

In the first part, I covered the essentials to getting started with the rapid web application development platform known as Mendix.

We’re going to expand out the app we started in the first part, and explore new concepts with it, such as Attribute Associations, Data grid columns, and Microflows.

Let’s get going!

Orders module

It’s good to divide your app up into different functional areas using modules. Modules incur no performance hit or overhead, they are simply a grouping of the various functional parts of your app.

Each module will have its own domain model, but that doesn’t mean we can’t reference entities in a different module’s domain model, it simply helps us organize something complicated: our application.

To create a new module, right click on the Project node in the Project Explorer panel:

Name the module “Orders”.

Now let’s open up the Orders domain model and add an order entity with the following attributes:

Note on the OrderNumber attribute, we don’t need to create a unique id for each entity, Mendix does that behind the scenes, and manages all the associations that go along with it. However, in this case, it makes sense to store an additional ID, like a deli counter number so that we have a quick point of reference for our order.

In other cases you may have a unique identifier already as part of your process, maybe its an alphanumeric string. No problem, you can add it and put constraints around it, but Mendix will still store a unique numeric id behind the scenes in the application database.

Note: Mendix uses HSQL as its default database, however, this can be reconfigured to point to another kind of database such as Postgres, etc.

By using the AutoNumber data type, Mendix will create an auto-increment number field and increment it each time it creates a new instance of that entity.

OrderLine

We have an Item entity, and we have an Order entity, and we need to associate the two, but let’s think about this: we need another entity that records the association from the Order to the Item. We need OrderLine because an Order may or may not be associated to an Item, and there will likely be additional data such as Quantity, and other fields that qualify the order’s relationship with the Item.

So lets start with the simplest concept of an order line:

Associating two entities

Obviously, OrderLine is going to be associated to Order, but the direction matters because it implies the child->parent relationship. Since OrderLine is the child of Order, let’s create an association by hovering the mouse over the edge of OrderLine, then clicking and dragging to Order:

Double click on the name of the association, which defaults to <ChildEntity>_<ParentEntity> (in the case above, it’s adding a 2 because it knows I did this already), and the settings for the association will open in a dialog window:

The Multiplicity of the dialog is the most important part. Since we drew a child to parent relationship, it defaulted to “one Order object is associated with multiple OrderLine objects”, which is true.

The delete behaviors are also worth noting. How should Mendix handle related data when part of that data gets deleted?

Well, it’s usually a better practice not to delete database records. We can always flag them and exclude them, and this is a better way, but if you have a good use-case for actually deleting the records, you will need to consider Mendix’s association deletion behaviors.

OrderLine to Item

We need another association to our Item entity, which lives in our Inventory Module. This time, we are not looking for a one to many association. We are looking for a one-to-one association, because one order line will refer to a single item.

We can’t draw this association as we did above, but Mendix has another way to create associations; double click on the item go to the Associations tab, and click New:

The Select Entity dialog will pop up as soon as you click New, and you can navigate to your Item entity under the Inventory module.

When the new association appears in the Associations list, you can double click on its name and edit the Multiplicity to be [1 – 1]:

Now, it probably would be better if we did the association from Item to OrderLine, but for 1 to 1 associations this doesn’t matter as much, because, as you can see from the delete behaviors, Mendix can handle either parent->child scenario.

Our Orders domain model draws a line from OrderLine going off the screen because it is referencing another domain model’s entity:

Simple though it may be, this is all we need to get going on our UI.

A UI for taking orders

Add a new page to the Orders module, and call it Orders_Overview. As before, remove that junk content that it creates with:

Don’t forget to set a page title in the Page properties!

Learn from my shortcomings: if you remember nothing else, title your pages.

Add a Data grid widget to the region you emptied, and associate it to the Order entity:

Double click on the title area of the data grid widget (where it says [Unknown]), and go to the Data source tab to Select the Entity.

Mendix will again offer to populate the Data grid columns for you based on the attributes it finds in Orders, you will, of course, agree, and the result will look like this:

We don’t need all the search fields, just Order number and Status will do fine:

OrderLine’s New/Edit page

Same as before, we want to auto-generate a New/Edit page for order by right clicking on the New button and choosing “Generate page…”

Select from the layout from the dialog’s form options:

I like Form Vertical

Remove most fields from this page except for the OrderNumber AutoNumber (which can’t be edited anyway because its a read only field). And add a data grid.

In the data source tab, specify Over Association, and select DataLine, this will instruct the widget to only display OrderLines associated with the Order for which the page was opened (a new order or edited order).

When you click okay, and say Yes to the prompt about automatically filling the grid’s columns, you should see the single attribute belonging to OrderLine, Quantity:

Only one field in OrderLine

You’ll need to add columns related to Item, which are over the 1-to-1 association between OrderLine and Item. To do this, first add a new column by right clicking on the column header line, and the choosing Add column left or Add column right:

Right click on the new column and choose Select attribute, then you will prompted for the caption of the column and the source of information you want to add, which is specified as the Attribute (path).

Choose the Name attribute from Item, which will appear under the OrderLine_Item association

Go ahead and add the Price attribute to the data grid as well.

Okay, but where are the action buttons?

You’ll notice that, unlike the Data grid widget with a Database Entity source, the data by association doesn’t have any buttons out of the gate.

We will make them.

Right click on the gray “button bar” above the data grid column headers and select from context menu Add button > Create. Now our New button shows up:

On the New button, right click and choose our friend “Generate page…” and choose the page layout from the list of form options:

Now this result is interesting:

…well, not that interesting.

It created a form with Quantity from OrderLine, and Name from item, which is convenient. It chose the Name attribute because that’s the first string attribute it found on Item, and it knows it needs to give you a selection for Item because OrderLine has an association.

You should probably drag Item above Quantity though. Also, change the page layout in the Page Properties panel to be PopupLayout (Canvas widthxheight of 700×500 is good).

Now let’s build and run our program…but before we do, two last things…

1. Get rid of this Add button on our Orders page because it doesn’t know what to add, and it’s not all that useful.

2. Remember to add an option in the Project Navigation for our Orders page:

Build and run

When you run the app, you will be prompted to synchronize the database because you added new entities. There is no sane reason for not doing this.

With the app built, and running, click on our new Orders navigation option, and click the new button on the Orders page.

Then, on the New/Edit Order page, click the New button above the OrderLine data grid.

You are presented with our current inventory of items.

However, when you save the order, and return to the Orders page, you will see that there is some missing functionality: Total cost is not updating. Also, there’s no option to pay for the order.

We’ll return to total cost. Let’s tackle the pay option first using a Microflow.

Microflows

If you’re a developer, let’s get some frustrating realities about Mendix out of the way:

  1. There is no code to write, only expressions in Microflows (similar to Excel formulas)
  2. You cannot enter a Microflow via text, you must graph it out via the Microflow editor.
  3. Microflows can get complicated, and you still have only the Microflow editor in which to manage them.

From the reactions I’ve seen from developers, Microflows are by far the bitterest pill to swallow. Part of the reason is simply that developers like to code, and Mendix basically doesn’t allow it (unless you are willing to step down into the Java layer, which sometimes is a good idea).

Just, put the apprehension aside and let’s get started.

In the project explorer add a new Microflow by right clicking on the Orders module and choosing “Add microflow…”

Call your microflow MF_PayForOrder

The convention I use and have seen used is to prefix microflows with MF_ for Microflow function (something is processed), or MC_ for Microflow calculation, which is used by attributes with calculated values, and also MV_ for microflow validation, which are used when we want to validate form data.

Inside the Microflow

All Microflows have a start point, one or more end points, and one or more Actions.

The Microflow will resemble any flow diagram you’ve ever graphed in Visio, the difference is it will actually be doing the actions listed in it.

For our current case, we need the microflow to action upon an order, and mark it as Paid.

This can only happen by receiving a parameter, which appears as the yellow shape indicated in the diagram above. Click on that and click again to set put it into the microflow, usually we put these above the start point:

As soon as you set it down, the Parameter Settings dialog will pop open and you will be asked to specify what Entity is being passed in. Choose Order, and you will see that the variable name is automatically populated (although it can be renamed), and it will be known throughout the logic flow using this name.

I’m going to rename it as OrderParam, just for clarity’s sake, and you will see that it shows both the variable name and the type below the parameter.

Next, click the little blue icon next to the arrow to create an action. Move the mouse to the middle of the microflow line and click again to insert the action. Then you will be prompted to choose the type of action:

There are LOTS of options for an Action, and it’s easy to get overwhelmed. In our case, we are going to choose Change Object, because we want to change the values of the entity’s attribute. For this we must select the variable the action will apply to:

You also need to consider if you want to store the change right away in the database, or if the change is part of a bigger set of changes, whereby it should be committed later.

Furthermore, when the change happens, do you need to update the UI right away? If so, choose Yes for Refresh in client.

Finally, specify the attributes to change (only Status here) by clicking the New button above the attribute change list field.

For the member attribute, select Status. Since Status is an enumeration, we need to specify one of its values (NotPaid, Paid, Cancelled). You can do so by typing the module name (Orders) and then typing a dot will bring up the data fields available within that module (constants, enumerations), and finally another dot will bring up the enumeration’s possible values.

Let’s set it to Paid:

Orders.OrderStatus.Paid

In addition to setting this value, let’s commit the object right away (set Commit to Yes), and also refresh the UI (Refresh in client to Yes) so the order will reflect the change in status to the user immediately:

Note that the action will represent both of these settings in the top right corner, as an up arrow for commit, and a circling arrow for refresh in client.

Wiring up our Microflow

We have the logic to change the Order, but where is it going to be executed? Let’s add a [Paid] button to our Orders page:

Make sure you click on the button bar and not another element in order to get the right context menu

The button will appear with the label “Action”. Double click on the button to edit it, and in the settings of the dialog, set the caption to Paid, and go down to the on click event and select Call a microflow:

Some people have “Do nothing” as a default setting also

When you select Call a microflow, you will be immediately prompted to choose the Microflow from our modules. Find MF_PayForOrder:

That’s it, save all and Build/Run it!

Paying for orders

Try out the new button on the Orders page. When you select an order and click it, the status should change to Paid:

One step closer to a second career as a burger stand cashier!

Next…

In the next part I will cover Microflow Actions in more depth, showing you how to calculate the total of the orders, as well as how to constrain the data so that it only shows under certain conditions.

Stay tuned.

Up and running fast with Mendix web apps (Part 1)

Preamble:

Mendix is a rapid web application development platform that will likely be hated by developers and loved by the business.

It will be hated by developers because it effectively trivializes what we do. It will be loved by the business because it delivers on the promise of rapid applications that work, and capture key data which can then be reported on or integrated with other applications.

I am sympathetic to the complaints of developers. The business always wants easy answers to difficult problems, and Mendix will not always be the solution they want, and it will be difficult to communicate the why’s when it’s not.

Be aware though: if the business is interested in it, stonewalling this option may cause more problems than embracing it, because there are plenty of vendors who don’t share your concerns, and Mendix is predominantly a cloud-hosted offering.

That said, if you are running a business where your associates are building a Tower of Babel out of excel files, you would benefit greatly from this platform. It is excellent at book keeping and handing transaction records. Better yet, because it is actually code free, there will be very little maintenance to speak of.

Mendix is worth exploring, and this guide will take you through what it is and how it works.

Essentials

Mendix is free to develop with, it only costs money when you push the app to a Mendix server. There are on-premise offerings but it’s unlikely many customers are using them.

To get stared, you need a Mendix account. I recommend you sign up with your business email in the event you like the platform and want to discuss licensing.

Installing the Business Modeler

Once you sign up for a Mendix account, you need to install the Business Modeler which is the application used to develop a new Mendix app.
Mendix has the modeler on a rapid release schedule and versions change frequently.

Apps developed in newer versions cannot be assumed to be backwards compatible, nor can older apps be expected to load in newer versions of the app. It is important then to get the right version of Mendix if you are working on an existing app.

If you are creating a new app, it is advised that you get the latest version of Mendix Business Modeler.

You can find all versions of Mendix here: https://docs.mendix.com/releasenotes/desktop-modeler/

Logging in

If your installing Mendix because someone else invited you to collaborate on their project, you will see upon login a list of projects that you have been given access to. Otherwise, you will see the option to create a New App:

Creating a new app

Mendix has templates to start from, but let’s make it simple and choose the uninspiring Blank gray app icon to start.

Like buying the Brand-X cereal at the grocery store.

Next you will be prompted to name your app, and make sure you enable Online Services which allows for version control, and collaboration. The only time you would not want this is if you are just working on a personal project.

Note: saying no to this option still allows you to deploy to a cloud, it’s just not a dedicated cloud, and the resources allocated to it will be transient. It may go dormant during periods of no use, and then it will take a minute to spin back up when you access it again.

Inside the Business Modeler

With your app created, you will see the main project view, which includes several functional panels.

You can rearrange these for better space efficiency, for example, the central panel can use more space, so the project explorer and properties panel can shrink down, and you can drag Console and Debugger into the button so they have more horizontal room.

I like the following setup, and use the panel pins to hide areas when I don’t need to see them. The center, content panel is the most commonly used one, followed by Project Explorer, which will fill up quickly with content:

The Error tab is important to find because you cannot run your project if it any errors. Of course, Mendix will tell you that if you try.

Mendix Terminology (the basics)

  • Module – a grouping of functions (Microflows), content (pages, images, enumerations), and a database schema whose entities can be accessed from other module’s domain modules and Microflows
  • Microflow – a function that can perform actions on the database, on the UI and do basic logic
  • Page – a UI arrangement of input components and widgets, can be a full page or a pop-up dialog style page
  • Page Layout – a template for presentation of a page (for example, a standard web page or a popup page)
  • Snippet – a grouping of UI elements which can be used within a page. A good example is a snippet for a display of a record type that is to be repeated across the page depending on the number of records
  • Entity – a database table schema
  • Attribute – a database column, but using Mendix’s embellished data types
  • Association – a reference from one attribute to another Entity

Starter Project Modules

All projects are going to start out with the following content in the Project Explorer:

  • Project ‘YourProjectName’ node
    • Global project settings go here, including application Navigation, App Store Modules (external add-ins to extend Mendix), Security settings which govern what user roles can see what pages and Microflows (functions)
    • Security level begins in off state, which allows anyone to access, and is good for getting started, but most of the time you begin working on Security roles early on and will set this to Prototype / demo
  • System – holds some data schema related to users and logins; generally you leave this alone except to extend or change the application startup function (or Microflow, as Mendix calls functions).
  • MyFirstModule – has a Domain Model for quick start of database design (usually you want to create a new module though), a Home page for quick start layout of UI that will appear when the app runs, and an Images collection of pictures used in the stock Home page.

Using the Domain model editor

Always start with the data schema. You will be using entities, attributes, and associations. To add an entity, click the Entity button in the top left and a new entity will appear on the panel which you can drag around.

Try to contain your excitement.

Double click on this and you will be able to edit the properties of the entity:

  • Name – how the entity will be referred to throughout the app. Mendix likes capitalized values, and no spaces, such as MyEntity
  • Generalization – you can base entities on other entities which is similar to object oriented programming inheritance. This feature should be used conservatively because it can incur complexity and overhead quickly. Only use it when you need it.
  • Image – I’ve never used this.
  • Persistable – You don’t always want to keep your data, sometimes you want entities for temporary use. These will be managed by the app and stored in memory instead of in the database.
  • System members – fields that can be tracked automatically by Mendix. I have generally checked these off for main entities.
  • Documentation field – these will show up throughout the Mendix UI. If you populate them, Mendix can provide nice Javadoc documentation. It’s okay to leave this blank until your app matures.
  • The tabs appearing below these settings
    • Attributes – these are the fields of your Entity, they all need a type and have an optional default value, if the value is calculated and not stored, it will use a Microflow to determine its value. More often, you are not using calculated values but calculating them externally since it’s better app design.
    • Associations – are references to other entities. These are actually stored like attributes, but Mendix manages them separately because there are more conditions around them, such as how Mendix should behave when an entity with an association is deleted; should the associated records be deleted also? These cases can be specified.
    • Validation rules – you can specify that an attribute must be entered, but in most cases it is better to do this through UI functions.
    • Event handlers – events such as Create, Delete, Modify, and Rollback can trigger Microflows either before of after the event. This is very useful.
    • Indexes – this matters when you have a table with a lot of data

To add a new attribute, click on the New button in the Attributes tab:

We need an objective…

So we’ll create a simple order app to fill out this demo.

We already have an Item entity, we’ll need Order (which is linked to a user account), and also OrderLine, so we can have a many to one relationship between the Item and the Order, and we can also specify attributes like quantity.

But thinking ahead, it’s clear that items will need to be managed separately from orders. So lets make a new module for items. Right click on the Project node in the Project Explorer and choose Add module…

You will be prompted simply to provide a name, so we’ll call it ‘Inventory’.

The ‘Inventory’ module

The new Module will appear in the Explorer, and it will have a domain model ready to populate. You can cut and paste your Item entity into it.

We need a UI to manage the items; create them, modify them, and later on maybe have some other overview information.

Right click on the Inventory module and choose Add page…

Mendix presents a smorgasbord of templates to choose from, and that’s overwhelming. So let’s go with the standard option; choose List in the left-side navigation, and select List Default:

Why do we keep choosing the boring stuff?

The new page will appear with some default elements like a title, and a paragraph / subtitle. But before you get going, give the page a title in the properties panel! Let’s call it “Inventory Management”.

I always forget to do this!

You can quickly edit the page by giving it title text and a sub heading. Just click on those elements and start typing and it will overwrite the text.

Then delete that content within the box below this, and move your mouse over to the toolbox tab that appears on the right edge of the app, click or hover over this tab and the toolbox pain will appear, filled with (SO MANY) widgets to use on your page.

The page will have a bunch of filler content to start. Clear the stuff within the region below the page title and sub title.

We’ll use a simple out-of-the-box widget called Data grid, which gives a very standard table presentation of an Entity’s records. Drag it to the region you cleared.

You’ll also notice the number headings over the content regions. These are Bootstap related. Mendix outputs the page content into Bootstrap’s 12 column layout to facilitate responsive web design. This way, the content will wrap as needed, depending on the size of the screen.

Mendix really forces you to adhere to this by requiring columns add up to 12 and telling you when they don’t. But don’t be mad, responsive web design is the inescapable reality of the Internet.

The Widget’s Data Source

When you drag the Data grid into the box, it will show up in the most general way, with no idea what to display. Double click on it to set its Data source, click the [Select…] button next to the Entity (path) field, and choose the Entity in the Select dialog.

As it turns out, Item is our only option anyways.

Mendix will prompt you if you want to auto-populate the table columns with the fields of Item. Yes, that’s helpful!

I also want to automatically fill the contents of my tax forms…

Now the data grid appears with columns found in Item:

OutOfStock attribute is out of screenshot

The New/Edit page

It’s pretty obvious Mendix has the ability to show a bunch of data from a table in this data grid widget, big whoop. But where the platform starts to shine is how simple it makes creation of pages to fill out that data.

Let’s setup its New/Edit page for Item. All we need to do is right-click on the New button that appears in the data grid, and choose Generate page…

This will give you the page dialog again, this time showing only forms in the left-side navigation, and we are going to choose Form Vertical for a nice vertical display of each field:

Notice that the Page name is prepopulated to be <EntityName>_NewEdit

This one action will:

  • Create the new/edit page that can save the record to the database
  • Wire up the New button to launch it in the web app
  • Wire up the Edit button to launch it in the web app for an existing record
  • No code

Take a look at the page properties by clicking outside the actionable area of the page (either the darkened region above or the blank region to the right). Otherwise you will may be looking at the properties of a selected element.

With the page properties showing, look at the Layout field.

The page layout it’s using (Atlas_Default) will cause the web application to open a new page when the item is created or edited.

It would be a better UX to just have a popup since Item is not a complicated entity with many fields and logic. If you click on the page layout’s value, you can select a popup layout.

Find PopupLayout in the Select dialog:


Use the Filter search to make it easier to find

Also, edit the Canvas width and height properties so that our popup is reasonably sized. The popup layout will scroll the content if needed, but we’ll be fine with the minimum Mendix popup layout size: 600w x 500h.

Save All, and we can test run the app!

Building and running(?)

Go to the Run button at the top center of the app menu, and select Run Locally. The project begins to compile…and finds some errors.

You can look at these in the Errors tab that appears at the bottom left of the application. Double click on the error and it shows you the context.

Green Add button doesn’t know what to do with itself.

One problem is that the Add button we left on our Inventory Management page doesn’t know what to add. We have to tell it the entity. Right click on it and choose Select entity… and choose Item from our Inventory module. The other error is it doesn’t know what page to use for adding a new Item. Conveniently, we can use our Item_NewEdit page which Mendix helpfully generated. Find it under the Inventory module and select it.

Now you will see that all errors are gone. Let’s try running it now.

Go to the top of the business modeler, in the middle of the menu select the drop down next to the Run button and choose Run Locally from the drop down:

The other Run option sends the build to the Mendix cloud

This will cause Mendix to build the application as a local Apache web server, and initialize that server so we can see it in our browser on localhost.

Note: the other Run option sends our build to the Mendix development cloud to be hosted, which is also fine because we don’t have to pay for hosting until we want to deploy our app to a dedicated hosting node.

Your app should now build with no issue, but you will need to wait until the web server is up and running (Mendix builds and runs an Apache server for each app), and it takes time.

Also, the first time you successfully run your app, Mendix will ask if you want to create a default database for it. Of course you do!

Filed under questions you probably shouldn’t say ‘No’ to.

After a little more building, it will prompt you that it’s ready to show itself. You’ll know because it will tell you:

There are options for Viewing so that you can see your app behaving as it would on a mobile-sized screen, but usually we’re going with the Responsive Browser:

This will launch you browser and show your running app.

First run of your app

Well…this sucks.

We need to make our new page available.

Navigation needs your new page

We have a page to create and edit items, or so it appears we do, but the user currently has no way of getting to your Inventory Management page.

It must be added in the Navigation node under the Project node:

On this screen click New item under menu, and add the following, selecting your Inventory Management page:

Now our Navigation Items list will look like this:

Our inventory must be of the edible variety…

Save all changes, and build/run it again by click Run locally.

Using our Inventory Management screen

Now when you run the app, your new navigation item will appear. And when you click it, the page will:

It looks good for zero custom design work, and it works.

Click the green Add button or the New button to add an item and the Item New/Edit page pops up, ready for settings:

The ubiquitous stock of hamburger inventory

Set the Name, set the Price, set the In/Out-off Stock, click Save and our item is added to our inventory: 

Let’s add more items:

It’s all about the beverage sales.

To edit an item, click it and click the Edit button:

AKA “The Bladder Buster”

Recap of Part 1

You can probably imagine easily some problems with the setup as is.

  • First of all, only certain people should ever see this page (that’s were security roles come in).
  • Secondly, what if a lazy employee adds a duplicate product (validation rules)
  • Thirdly, what about tracking changes made to the product (more app/data design needed)

…And so on. These are important questions that you should be asking in order to make a better app. But we’re not going to cover them here.

In the next part, I will build the Ordering functionality of our app which will allow you at the very least to handle the IT needs of your fledgling burger business.

We will cover associations, Microflows, nested data widgets, and data source constraints.

Go to Part 2 >>


JSONP with Mendix REST Services

Mendix is an exciting platform because it simplifies something that tends to get overly-complicated: web-facing, record-based systems.

Because of Mendix’s platform ideology of rapid development, it isolates the developer from the guts of the java code it generates and compiles.

The problem is that many of the apps (modules) available from the App Store are not as flexible or feature rich as they might be, and some have the classic problem of backwards compatibility with a rapid-release IDE (in this case, the Mendix Business Modeler).

When Mendix started offering REST services, I took interest because it’s one of the better use cases for the platform, and I found that the REST Service module delivered both consume and publish services, and the setup was intuitive and worked well…with one exception: No JSONP support.

JSONP is a very simple modification to JSON output that simply wraps the JSON object of the response in a function name that you pass to it in a parameter usually named callback.

So we go from

[{"field1":"stringvalue", "field2":100}]

to

passedCallbackFunctionName([{"field1":"stringvalue", "field2":100}]);

Then, on the receiving side, the function named in the query parameters is either automatically invoked by libraries like jQuery (because it detects a parameter named callback in the request url), or manually by calling eval() on the response body.

This can be fixed, but requires an adventure into the java code layer that Mendix generally keeps out of sight.

To setup REST in Mendix, first download the Rest Services module from the App Store:

mendix-rest-services-module

With this downloaded, you will see the following content in the tree view of the module in the Project Explorer:

mendix-rest-module-tree

You want to create a microflow to handle the initialization of your REST microflow endpoints, and set that in the Project Settings After startup property:

mendix-project-settings-after-startup.jpg

 

My Initialization microflow looks like this:

mendix-rest-init-microflow

The first activity takes no parameters. The second needs and third need settings similar to the following:

mendix-rest-create-microflow-service-action-settings

So in my module named Search, I am exposing a microflow named “incidents”; giving it a wildcard for security role, which means anyone can access it; being unimaginative with my description; and specifying HttpMethod of RestServices.HttpMethod.GET enum value.

I do this again for another endpoint that serves up records from a entity table of requests.

I’m not going to go into the mechanics of the microflows I’m publishing, except to note that they produce JSON based on the fields of a non-persistable entity, which I populate via a persistable entity at the time of endpoint invocation. For this simple ticket system app, my domain model looks like this:

mendix-rest-domain-entities

The search args will be automatically populated, based on the parameters in the query string.

For example, when you hit the running endpoint and specify contenttype=json, you get this result:

http://localhost:8080/rest/incidents?firstname=James&lastname=Gilbert&limit=10&offset=0&status=Open&q=&contenttype=json

mendix-rest-query-results

So the service publishes under the path

http://<your-app>/rest/<microflow>

…But as you can see, this is not JSONP.

 

To have Mendix Rest Services offer JSONP support, you only need to make two tiny edits to the files RestServiceRequest.java, and RestServices.java which are added to your Mendix project when you add the Rest Services module.

To find this, go to the Project menu, and choose Show Project Directory in Explorer

mendix-show-project-directory.jpg

And navigate to

<Your Project Path>\javasource\restservices

mendix-rest-path

There’s RestServices.java, and RestServiceRequest.java is under the publish folder.

Add the following to RestServices.java:

mendix-rest-RestServices-java

And in RestServiceRequest.java, here are the changes:

mendix-rest-RestServiceRequest-edit1mendix-rest-RestServiceRequest-edit2mendix-rest-RestServiceRequest-edit3mendix-rest-RestServiceRequest-edit4

Here’s a zip of all the changes: Link

When you have your service compiling and running locally, you can deploy it to the Mendix Free App Cloud for further testing. NOTE: the service will go to sleep after a period without requests, so as tempting as it is, it’s probably a bad idea to leave it on the free app cloud.

So now you can make ajax calls your Mendix REST service endpoints from jQuery without worrying about Cross-Domain requests, which ajax now blocks.

Here’s a sample of one such request:

var mendixurlbase = "https://<your-hosted-app>/rest/incidents?callback=?";
$.getJSON( mendixurl, { 
    firstname: "James",
    lastname: "Gilbert",
    limit: 10,
    offset: 0,
    status: "Open",
    contenttype: "json"
}) .done(function( data ) {
    console.log(data);
});