Search This Blog

Create forms with Websharper.Forms

Create forms with Websharper.Forms

In my previous posts, I have covered multiple aspects on how WebSharper can be used to make nice webapps by using animations,
by tapping into external JS libaries or by using the built in router in UI.Next to make SPA.
Today I would like to cover another aspect which is essential for making useful webapps - Forms.

Most of the site we visit on a daily basis have forms. WebSharper.Forms is a library fully integrated with the reactive model of UI.Next which
brings composition of forms to the next level by making composition of forms, handling validation,
handling submit and displaying error an easy task.

Basically, it allows us to work directly with the input validated data in the function given in Form.Return.
Every interaction is done by composing Form<_> and we compose Form<_> elements.
Since validation on the inputs is done at the Form.Yield level, the values given to the function in Form.Return are always valid and we can safely work with the values.

If our input is a string input, Form.Yield "" will return a Form<string,_> and within the function in Form.Return we can directly work with the string given by the Form.Yield.

Now it is interesting to look at the type to see how the composition works, the first Form.Return has the following type:

And it turns out that string * int is our inputs combined in a tuple that we receive as argument in Form.MapAsync
and Var<string> -> Var<string> -> Var<int> is what we receive in Form.Render to render our form.
Wonderful, it seems to add up together!

Inline validation

Inline validation refers to the validation of the fields before being sent. It will help to prevent submitting the form for nothing.
I might be stating the obvious but the server should still perform a validation on the input sent.

Validation is handled during Form.Yield piped to Validation.XX.

<*> (Form.Yield "" |> Validation.IsNotEmpty "Last name is required.")

What happens when data is invalid?

That’s the amazing part, when data is invalid, the function in the Form.Return isn’t executed.
Instead a Failure is passed through and can be caught in a Form.MapResult or directly in the Form.Render to be display the error.
That is why we can safely assume that all the arguments in the Form.Return function are valid arguments and we can perform the action we want.

Mapping async function and result

Most of the time when sending a form we want to perfom a network request.
Those requests are usually async request. Form.MapAsync allows us to specify an async function to be executed when the form is submitted.
This allows us to handle the result in Form.MapToResult without worrying about the async nature of the call.
Form.MapToResult is piped to perform an action when the result of the async function is returned.

Submitting data

When we want to use a submit button and we want the form to be triggered when that submit button is clicked,
we need to pipe a Form.WithSubmit function. This adds a special type at the end of the arguments of 'D.
The type becomes:

The Submitter type exposes a Trigger function which allows the form to be triggered and a View which observe the Result<'T> of the form.
A Submitter is just a type hiding a View.SnapshotOn where Trigger triggers the snapshot of the current value of the form.
If you are interested, you can find its definition here.

The View can be used to display inline errors and errors returned from the async call.

I pipe the submit after the Form.Map otherwise you need to use Form.TransmitView to observe the error which occurs during the mapping.
Also if you pipe the submit after the Form.Map be sure to add at least one validation otherwise the Form.Map will be executed one time on startup.

|> Form.WithSubmit

Render

Finally we render the form and transform it to a Doc. As we seen earlier, the arguments of the Form.Render function are the Var<_>(s) plus a Submitter.
We basically construct the form and call .Trigger on click.

Some helpers

The Render call contains some extra functions, Doc.ShowErrorInline and Doc.ShowCustomErrors.
These functions are extensions that I have created to simplify the display of errors.
Here’s the implementation:

View.Through will filter the errors which are only related to the Var<_> given.
I am using a cutomErrorId to filter the errors that I created myself.

The full code source can be found here .

Conclusion

At first WebSharper.Forms looks intimidating, especially when you are not familiar with the apply notation.
But the concepts used in WebSharper.Forms is very powerful as it allows us to hide behind the Form<_> type and manipulate safe values to perform our actions.
The only validation needed is the validation during the Yield stage.
After getting used to it, I found the use of WebSharper.Forms very beneficial as
it allowed me to rapidly build form flows and even after few weeks,
I can just have a glance at the code and directly understand what it is doing
(and we all know that it does not happen with every piece of code). Like always, if you have any comments, don’t hesitate to hit me on Twitter @Kimserey_Lam or leave a comment below.
Thanks for reading!

Post a Comment

Popular posts from this blog

Absolute layout and relative layout Xamarin formsIn Xamarin Forms, layouts are used to position elements in the page.
There are multiple layouts available like stack layout, grid layout, table layout, absolute layout and relative layout.
Stack layout is straight to grasp the concept, we stack elements one by one horizontally or vertically.
Grid layout is also straight forward, we define rows and columns and we place the elements by indicating the row index and column index.
On the other hand, absolute layout and relative layout isn’t that straight forward because in Xamarin it is NOT the same as positions in CSS.So today, we will see how and when we can use absolute layout and/or relative layout in our advantage.
This post is composed by two parts: 1. Absolute layout
2. Relative layout
1. Absolute layoutThe first thing to understand is that absolute layout has nothing to do with CSS absolute position.
In Xamarin Forms. absolute layout allows us to position elements in the page by pre…

Build an accordion view in Xamarin.FormsFew weeks ago I posted about absolute and relative layouts.
Layouts are called Layouts because they contain children which are placed in a particular way.
Xamarin.Forms has a lot of layouts and views to structure pages like grid, table view or list view.Today I would like to show you how we can use some of these basic views to build an Accordion view.Here’s a preview of the Accordion view:Full source code available on GitHub - https://github.com/Kimserey/AccordionView/blob/master/Accordion/AccordionView.csThis post will be composed of four steps:Create a BindablePropertyDefine the accordion expandable sectionDefine the accordion viewUsage sample1. Create a BindablePropertyAs we saw in one of my previous post,
Xamarin.Forms works around data bindings.
View properties are bound to viewmodel properties.Default views like Label, Button, ListView or TableView come with the necessary bindable properties like BackgroundColor, TextColor, ItemsSource, It…

Use Font Awesome from your Xamarin.Forms projectIcons are important in mobile applications where space is limited.
We use icon everywhere to convey action intent like + would be to add an item or a bin would be to delete one.
There are two ways to add icons to our mobile app:with imageswith fontsToday we will see the second option - how we can add Font awesome to our Xamarin.Android project and how we can use it from Xamarin.Forms.
This post will be composed by three parts: 1. Why Font Awesome
2. Add Font Awesome to the Droid project
3. Use with Xamarin.Forms
1. Why Font AwesomeIf you are familiar with Web development, you must have encountered Font awesome http://fontawesome.io/.
It is an icon font containing lots of icon for every type of usage.
The advantaged of using a font is that we can leverage the text options, like text color or text size, to easily update the style of the icon to match our app.Let’s see how we can bring Font Awesome to the Droid project.2. Add Font awesome…