2008-03-01

Handling user roles in the UI

I've seen this question asked on Flexcoders many times: how do you show/hide various parts of the application? And normally the person asking this question is proposing some complex solution when in fact the answer is simple. First step is to load all the roles for the user from the server-side and then maintain them in some class, typically a User class, like so:

public class User {
...
public var roles:ArrayCollection;
...
}

In a simple scenario, every role is just a string that is held in the roles list as you can see from the sample code above. However, every application is different and it may be more complex in your case.

Next your User class should have a function name isUserInRole( role:String ), analogous to the method used in JSP/Servlets for J2EE applications. This function should take the role provided and make sure it exists in the roles list for the user. If it does, the function should return true, otherwise it returns false.

The final part is to use this logic on various containers and controls. Say you want to give or restrict access to a Save button in your application, your code might look like so:

<mx:Button enable="{user.isUserInRole('EDIT_ITEM')}"/>

In the example above the button will be enabled only if the user has the EDIT_ITEM role. It is that simple.

Some extra things to consider, sometimes you want to completely hide the container/control, so you have to apply the same logic as above but to the visible property of the container/control. One final trick is if you don't want the container/control to take up any space while it is hidden, set its includeInLayout property the same way.

Printing TextArea content

Just this past week an issue in one of our applications was pointed out to me. The feature allows a user to print the contents of a TextArea control, however it does not handle multi-page printing, meaning when the contents of the TextArea actually spans several printing pages. So I started working on adding this capability but after a while was wondering why I wasting my time and starting googling for this solution, since someone must have already done it. Didn't take long to find it actually. Someone has created a PrintTextArea control and included it as part of a project called FlexReport, which you can find here. Only one problem, the website contains no SWC file to download, so I just copied the code and compiled it as a library and used it in my project. I recommend you do the same, before this source code is lost, as this is a very useful control. Many thanks to the developer who created it, wherever you are :)