Friday, February 1, 2013

Using forms with Play framework 2 and Twitter's Bootstrap

I've been trying to learn Twitter's Bootstrap, Play2, and Scala for the past month. The past two days, I've been trying to create a basic HTML application along with a controller, model, persistant layer, and HTML form. It took me a bit of time to really understand what was going on, but I think I finally got it. The form is a basic "Contact Us" and here are the requirements:

  • User should prompt to enter a contact form: name, e-mail, phone, and comment
  • Form should validated any errors and report a friendly message in case of such error
  • Display a message back to the user that the information was indeed saved

Here is what my controllers will have:

  • A form with all the validation
  • A controller that will take the user to the form page
  • A controller that will validate the form, and either send it back to the form's page in case of an error, or display a successful messages in the details page
  • A controller that will act as an "edit" page, which displays the form information successfully saved

First, lets start with the form. We have a "contactForm" which only needs to have:

  • Client's name - required field
  • Client's e-mail - required field and validates if it's already in our contact list
  • Client's phone number - required field
  • Comments - anything that the client can tell us about his/her firm and reason of reaching us

However, the model that we have, needs to have more than these fields. For example, we need to have an ID, and also a signed-up date that tell us when the customer registered with us.

The model application will look like this:

However, because the id, comments, and signedup fields are not required, we need to add Scala's "Option" field. The reason of this wrapper is to avoid "nulls". This tells the application that the field is not required and that it might be null. This will also come in hand with our SQL and with the form fields in the controller. Here is how the model will look like:

Now, we need to take care of the persistent layer (DAO/Repos). This layer will take care of displaying all the contacts, retrieve contact by e-mail, and insert a contact into our database.

For this example, I will be using the h2 database provided by the Play framework. You need to comment the following lines in the conf/application.conf

Since, I will be using Anorm, we need to create the SQL script for your SQL evolutions. You need to create a folder "conf/evolutions/default" and add a file 1.SQL with the following code:

Now, we can create the rest of the model:

Inside the object method, you will find the simple mapper. This is simply mapping each of the SQL record. It is important to be consistent with the case class. The method's purpose can be seen in the findAll implementation. The application will respond with a sequence of contacts, by executing an SQL statement, and calling the simple to all records (hence the "*") to be map using the "simple" mapping.

The findByMail is a bit different. The main purpose of the method is to find out if there are no records for this e-mail. To avoid null or empty validations, it's recommended to use Scala's "Option" wrapper. This is why we will add the Option[Contact] as our return statement, and the "headOption" when returning the response. This will be very helpful for our form as we will see next. Otherwise, you will get errors similar to this one:

Now that we have our model and persistent layer, here is the controller code:

As you can see, the form will be doing the validation for each field. Here's is where I failed: I was under the impression that I should only have the fields that were in my form. It so happens, that the Contact.apply and Contact.unapply is mapped to the case class; therefore, you need to specify all the fields. This type of error caused the following message:

Now, for the validation, we need to add is the id as optional since this will be given by the DB when creating the record. Next is the e-mail validation. As requested, there needs to be a validation in case the e-mail has been recorded previously, and return a friendly error message. The email calls a "verifying" method that takes two parameters. One is the error message in the case that the field is not valid. The second parameter is a boolean that checks the validity of the value. In the case of the e-mail, we check if it's in the database - "Contact.findByEmail(_).isEmpty". The "isEmpty" method is provided by "Option" wrapper - in case if it's null or empty, it will be true.

The "newContact" controller will take care of displaying the form. It also sends the form back in case there are any errors. This is why we add the "implicit request". We will be using the flash for a temporary storage of the error.

Most modern web-frameworks have a flash-scope. Like the session-scope it is meant to keep data, related to the client, outside of the context of a single request. The difference is that the flash-scope is kept for the next request only, after which it's removed. This takes some effort away from you, as the developer, because you don't have to write code that clears things like one-time message from the session.

Play implements this in the form of a cookie that's cleared on every response, except for the response that sets it. The reason for using a cookie is scalability. If the flash is not stored in the server, each of one of a client's requests can be handled by a different server, without having synchronize between servers.The session is kept in a cookie for exactly the same reason. This makes setting a cluster a lot simpler. You don't need to send a particular client's request to the same server, you can simply hand out requests to servers on a round-robin basis.

Now, lets look at the "create" controller. This will be the action called by the form. The application will get the HTTP request, and bind the request. Then, it will call the fold command to see if the form values have errors or if it's successful. In Scala "fold" is often used as the name of a method that collapses (or folds) multiple possible values into a single value. The fold method has two parameters, both of which are functions. So, "hasErrors" is called if validation failed, and "success" if it validates without errors

Below is the contact.scala.html code:

As I mentioned at the beginning, I'm using Twitter's Bootstrap to handle all the CSS and HTML5 goodness. Therefore, I want to leverage as much as possible all of that. To activate the CSS handling and using the helper functions for Play you need to import a few fields. Also, you need to add the form and flash scope parameter to the HTML. I also used the implicitFieldConstructor to show where the errors happened. We will show that later. First lets emphasize on the form. The actions for the form will be handle by "@helper.form(action = routes.ContactUs.create, 'id -> "validForm")". Then, we will add the fields by using the "fieldset". I wanted to leverage the uses of place holder, labels, and classes on all the input fields. However, the most important part is to know that @helper.inputText(contactForm("name")) consists on the name of the input. The id goes inside the "contactForm".

I also provided some type of error friendly validation in case the user has some erroneous fields. I created a "contacterror.scala.html" with the following code:

Then, I added the @implicitFieldConstructor = @{ FieldConstructor(contacterror.render) } in the form (contact.scala.html). Again, this way, we will see the highlights and the friendly errors on the fields.

Tuesday, January 29, 2013

Using templates with Play 2 and Scala

I admit, it has been a while since I have done web development. To be more precise, the last framework I used was Struts 1.x (back in early 2000's). It was the de facto MVC framework of its time, but I end up loving it when I found tiles. Tiles introduced the template format, and is one reason why I end up using Play 2 along with Scala in my new web applications. The use of templates is something that I really enjoy - makes my job a lot easier and more productive.

Lets say that you have a series of products to display. Your Play controller will look at something like this:

Now, lets assume that the app/views/catalog.scala.html contains the following: The code will show all the products, but also it shows the navigation, and footer. Clearly, we want to separate these contents so we can reuse them in another application. Furtheremore, in case that the footer has all the javascripts and Google analytics, we need to make sure that indeed all pages get tracked.

Using Play 2, you can simply extract all your navigation to a file name app/views/navigation.scala.html that will contain the navigation code:

Then, do the same thing with the fotter app/views/footer.scala.html: Now, to show the contents of the navigation and the footer, simply use the code @navigation() and @footer() to show the contents. The catalog.scala.html will now be like this:

The other reason that I really enjoy Play 2 with Scala is the reverse routing. Reverse routing is a way to programmatically access the routes configuration, to generate a URL for a given action method invocation. In other words, you can do reverse routing by writing Scala code!

As you can see in the navigation, I don't have any hard coded routes. For example, home has the link: "@routes.Application.home". This is perfect in case of refactoring! My routes for home and catalog will depend on the configuration of my routes (contained in the conf directory):

If tomorrow I want to change the path, that will not affect my code at all, just the route file.

Again, this is an efficient way of programming because you can leverage the templates to build a user-interface view and you can use user-friendly URL with the help of your routes.

Monday, January 28, 2013

Understanding the implicit on classes

When I was learning Scala I stumbled into the implicit keyword. It took me a bit to understand it, but I really got into it once I started using Play. The best way that I can explain it is by thinking about "extending" the class without actually changing the code. Here are some examples: This type of code is very useful. If you are using the Play framework, then you probably seem this type of code: In here, we are implicitly extending the HTTP request so we can inject a product list. This type of code is very useful because you can still have the Person class without been compromised (immutable/intact). The same goes for the example below: Using Anorm, we use implicit to use the SQL connection. However, as you can imagine, this can also have some problems. You can read more about it here.

Friday, December 21, 2012

Basic Anorm techniques using Scala

I started using Play! along with Scala and so I've been using Anorm as my ORM.  It reminds me very much of a project that I used, myBatis.  Anorm (not Another ORM) is a SQL data mapper.  

In my application, I need to create a summary of trades.  Here is the code for the controller and the model. The code uses a trade date (yyyymmmdd) to call the correct trade summary.

Controller:

Domain/model:

Tuesday, December 18, 2012

Playing around with Play framework

I did a presentation on the Play framework using Scala for the Miami Java User Group (JVM).  Below is the presentation along with the code to create a small application.

The first thing that you need to do is to download/install Scala and Play into your computer.

To create the application, go into your terminal console and do the following:
  1. play new foobar 
  2. Keep the same name of the application 
  3. Select the Scala template (1) 
  4. Change the directory to the foobar directory
  5. type "play run" 
  6. Go into http://localhost:9000 
You should be able to view the "Welcome" page for Play.

The structure is very similar to Ruby on Rails.
  • app: is the directory for all classes in the application 
    • controllers: all the controllers/actions for the applications 
    • models: domain objects 
    • views: the scala html pages 
  • conf: has all the properties files including the routes 
  • logs: the logs of the project 
  • project: build classes 
  • public: CSS and others 
  • target: compiled classes 

Looking at the conf/routes we can see the following: This says that the moment that the application goes to the "/" it will call the controller Application and invoke the "index" method.
The controller has the following code: The index method calls an Action and sends an OK, which is nothing but a HTTP 200 code, and calls the page views.html.index with the string parameter: "Your new application is ready".

If you look at the apps/views/index.scala.html you will see the following:
The message that was passed by the Application controller is stored in the message: String. The application calls a main html page and passes two parameters: "Welcome to Play 2.0" and "message".

If you look at the app/views/main.scala.html you can see that the first parameter is the "title" and the second parameter is the HTML content:
Remove the "@play20.welcome(message) so that the page looks like this: Render the page again, and you will see only the parameter passed by the controller. Lets go to the controller and edit the text by changing it to "Playing around".
Go back to the web browser and refresh the page. As you can see, the application renders automatically. The one thing that I like about the Scala programming language is that it is statically typed, so I can check in my editor. Lets configure the application as an Eclipse project.

Go to the console application and type control "D" or control "C" to stop the application. Now, type "play". You should see the play console. By typing "eclipsify" the play application will be ready to be imported as a project for Eclipse. Just go into Eclipse and import the project (file, import, select foobar directory). Once you are done type "run" to start the application.

As I mentioned, the conf/routes has the configuration for all the routes. If we add a route:
And go to http://localhost:9000/foo
You should see the same as if you go to http://localhost:9000.
Lets create an application that create a bar. The first thing we need to do is to create a model object named bar. Create a model by creating a Scala class in apps/models/Bar
The object will have only an id and a name. Now, we need to create a way to persist to a database. For Play the DB of choice is H2. It is a memory database and it is easy to work for development. To enable the database go to conf/application.conf and uncomment two fields:
Now that we have the drivers and the database, we need to create a script to create the database. Create a file for the DB schema inside conf/evolutions/default/1.sql
Refresh the page and you should be prompted to load up this script (or evolution). Just click on "apply this script now!"

Now, lets go back to the Bar model class and add the following:
This section will be the domain, which simply creates the bar and inserts it into the database. As you can see, we use the anorm API to map the SQL. This is not an ORM but more like a MyBatis (an SQL mapper).

Now, lets go to the Application controller and add the two things: the controller and the view. The first thing we need is to intercept the HTML form and add the action for the controller. Here we add the action and send a message depending on the type of transaction (error or success). We need to create the view form, but first we need to add the route to the controller.
Now, lets create the form view in the views/index.scala.html: You should be able to see the form in the application. Lets try to add a "test" bar. You shouldn't have any errors.

Now, we need to displays all the bars added. To do this, lets first modify our domain/model Bar object and controller. Using the allBars, we will be able to get all of the records from the bar table. For the controller, we will add the following: Now, we need to add the route in the conf/routes: If we go to http://localhost:9000/bars

You should be able to see something like this: We will want to render this URL and get all the JSON objects and put them into the index page asynchronously via CoffeeScript. First, lets create a folder app/assets/javascripts/index.coffee Here, the application will go to bars URL and fetch all the records, then it will iterate through the records, and append a list of all the bar names. Lets add the JavaScript header and bars into the index.scala.html

Now, lets add the JavaScript into the app/views/index.scala.html
You should be able to notice two things. You should be able to see all the inserted bars, and when you upload a bar, it should render automatically.

Wednesday, October 31, 2012

Groovy's Eclipse GroovyRuntimeException error with Log4J

When I updated my Eclipse's Juno plugins, all my Groovy projects came in with exception.   The error seems to be with the Log4J annotation "@log4j". This is what they said:


I was able to solve it by adding the latest snapshot here:

Once I was able to add this, all my errors went away.

Sunday, October 14, 2012

What is the product of your company? - is a byproduct

I follow Zach Holman, he works at GitHub. I follow him not because the guy is a techy, or because he works at GitHub, but because the guy just makes sense. Many of his blogs resonate through the different start-ups and companies I've worked. Specially, how to run a company which he talks in hist post the product is a byproduct.

I worked in many places that cared more about the "perception" of the company rather than the people. Many manager/directors worry about the image of the company without realizing that they are setting the tone of the company's culture (their workers), and this will affect their bottom-line/product. For example, "we expect you to work from 9 am - 6 pm", "we expect you to work AT the company, not at your house", "we expect you to dress a certain way - we have a dress code", "we need to ship this feature, we don't care how you get it done…that's your problem."

When we started a my former start-up, we thought we understood our customers, we thought we knew what they wanted, and we just wanted an application that WE would like. After all, "build it, and they will come", right? WRONG! The bottom line is that we were assholes. We really didn't have it right. It was until hard lessons learned that we started listening to our customers and focused on what they wanted rather on what we thought they wanted.  But also, it was until we started changing our culture and hiring the right people that the company finds its product.

Zach talked about things like:
Your product should be a byproduct of the people, process, and technology of your company.

Foster a good environment, be more likely to create a good product.

Hire those bothered by suck. You want fixers
I'm very committed to my companies, but I'm also in LOVE with my family. This is constant tough of war in my head. I do want to help the company in everything I can, but I also want to help my son with homework, and spend some time with my daughter and wife.  I do feel that where I work is MY company. I know that there are some people that said that it shouldn't be like this, "you shouldn't live for work, but work to live". But that's not what I mean. I work as it's my company in the perspective of shutting down my MacBook Pro,with the feeling of "I kicked ASS today".  It is not always like this, but most of the time, they are.   I like the fact that people (coworkers and directors) say, "ever since we hired Marcelo, this place is TIGHT", but I also want my family to say, "we love were you work, because we can see you and spend quality time with us".

As Zach mentions:
Any time you interview a potential hire, you need to ask yourself not only if they're talented or collaborative but also if they're capable of literally running this company, because they will." - VALVe

Hire broad people. Hire diverse people.

Good culture attracts good people

Be family friendly

Flexible location, hours, workload