How to Create a Sencha Touch 2 App, Part 3

In this third part of this tutorial on how to create a Sencha Touch application, we are going to create the Note Editor View. This is the View that will allow our users to create, edit and delete notes.

When we finish this article, our application will have the ability to create notes, and edit existing notes. Let’s get started building the Note Editor View.


Creating a Form Panel in Sencha Touch

We will place the View’s source code in the  NoteEditor.js file, which we will create in the view directory:

In the file, we will define an empty NoteEditor Class like so:

1 Ext.define("NotesApp.view.NoteEditor", {
2     extend: "Ext.form.Panel",
3     requires: "Ext.form.FieldSet",
4     alias: "widget.noteeditor",
5     config:{
6         scrollable:'vertical'
7     },
8     initialize: function () {
10         this.callParent(arguments);
12     }
13 });

The Note Editor is an extension of the Ext.form.Panel Class. As we will use a FieldSet Class instance in the View, we are asking the loader to download its source by using the requires config. We are also using the scrollable config to allow the contents of the Panel to scroll vertically. This stops the form from being cropped when its height is larger than the screen height of the device.

As we did with the Notes ListContainer Class, we are going to use the initialize() function to define the Note Editor’s components:

1 Ext.define("NotesApp.view.NoteEditor", {
2     extend: "Ext.form.Panel",
3     requires: "Ext.form.FieldSet",
4     alias: "widget.noteeditor",
5     config:{
6         scrollable:'vertical'
7     },
8     initialize: function () {
10         this.callParent(arguments);
12         var backButton = {
13             xtype: "button",
14             ui: "back",
15             text: "Home"
16         };
18         var saveButton = {
19             xtype: "button",
20             ui: "action",
21             text: "Save"
22         };
24         var topToolbar = {
25             xtype: "toolbar",
26             docked: "top",
27             title: "Edit Note",
28             items: [
29                 backButton,
30                 { xtype: "spacer" },
31                 saveButton
32             ]
33         };
35         var deleteButton = {
36             xtype: "button",
37             iconCls: "trash",
38             iconMask: true,
39             scope: this
40         };
42         var bottomToolbar = {
43             xtype: "toolbar",
44             docked: "bottom",
45             items: [
46                 deleteButton
47             ]
48         };
50         var noteTitleEditor = {
51             xtype: 'textfield',
52             name: 'title',
53             label: 'Title',
54             required: true
55         };
57         var noteNarrativeEditor = {
58             xtype: 'textareafield',
59             name: 'narrative',
60             label: 'Narrative'
61         };
63         this.add([
64             topToolbar,
65             { xtype: "fieldset",
66                 items: [noteTitleEditor, noteNarrativeEditor]
67             },
68             bottomToolbar
69         ]);
70     }
72 });

Within initialize(), after invoking callParent(), we proceed to define the top Toolbar, along with its two buttons, the Home Button and the Save Button. We then define the bottom Toolbar and the Delete Button.

The noteTitleEditor and noteNarrativeEditor are the fields we will use to edit the note’s title and narrative. They are instances of the Ext.form.Text and Ext.form.TextArea Classes.

Once all the View’s components are defined, we proceed to add them to the View. This is where we also add an Ext.form.FieldSet instance to enhance the appearance of the form. The title and narrative editors will render within the FieldSet:

1 this.add([
2     topToolbar,
3     { xtype: "fieldset",
4         items: [noteTitleEditor, noteNarrativeEditor]
5     },
6     bottomToolbar
7 ]);

Rendering a View In Sencha Touch

Before we start developing the features of the Note Editor, we are going to work on the code that will render this View when the New Button in the Notes List Container is tapped.

In the previous chapter of this tutorial we created the tap handler for the New Button, which fires the newNoteCommand event. We also added the onNewNoteCommand() listener to the Notes Controller. We will use this function to activate the Note Editor View.

To activate the Note Editor View in the Controller, we first need to acquire a reference to the View. We will use the noteeditor ref for this purpose:

1 Ext.define("NotesApp.controller.Notes", {
3     extend: "",
4     config: {
5         refs: {
6             // We're going to lookup our views by xtype.
7             notesListContainer: "noteslistcontainer",
8             noteEditor: "noteeditor"
9         },
11    // Remainder of the controller’s code omitted for brevity.
13 });

Remember, this ref automatically creates a getNoteEditor() function in the controller, which we can use to refer to the NoteEditor instance and make it the active View in the application.

Next, we need to modify the onNewNoteCommand() function:

1 onNewNoteCommand: function () {
3     console.log("onNewNoteCommand");
5     var now = new Date();
6     var noteId = (now.getTime()).toString() + (this.getRandomInt(0, 100)).toString();
8     var newNote = Ext.create("NotesApp.model.Note", {
9         id: noteId,
10         dateCreated: now,
11         title: "",
12         narrative: ""
13     });
15     this.activateNoteEditor(newNote);
16 }

Here things get more interesting. We are creating a new note, and passing it to the activateNoteEditor() function.

We are going to use the getRamdomInt() helper function to generate the unique id for a note:

1 getRandomInt: function (min, max) {
2     return Math.floor(Math.random() * (max - min + 1)) + min;
3 }

The activateNoteEditor() function will load the new note into the Note Editor, and make the Editor active:

1 activateNoteEditor: function (record) {
3     var noteEditor = this.getNoteEditor();
4     noteEditor.setRecord(record); // load() is deprecated.
5     Ext.Viewport.animateActiveItem(noteEditor, this.slideLeftTransition);
6 }

Here we are taking advantage of the Ext.form.Panel’s setRecord() function, which allows us to load the values of a model instance into the form’s fields whose names match those of the model’s fields.

This function also uses the slideLeftTransition variable, which we need to define like so:

1 slideLeftTransition: { type: 'slide', direction: 'left' }

The transition will bring the Note Editor into view with a slide motion from the right to the left.

This is all the Controller needs to do in order to activate the Note Editor View when the New Button is tapped. However, we need to make the application aware of the NoteEditor Class.

Making The Application Aware Of A View

In the app.js file, we will add the new View to the views config:

1 views: ["NotesList", "NotesListContainer", "NoteEditor"]

We are also going to instantiate the View in the Application’s launch function:

1 Ext.application({
2     name: "NotesApp",
4     models: ["Note"],
5     stores: ["Notes"],
6     controllers: ["Notes"],
7     views: ["NotesList", "NotesListContainer", "NoteEditor"],
9     launch: function () {
11         var notesListContainer = {
12             xtype: "noteslistcontainer"
13         };
14         var noteEditor = {
15             xtype: "noteeditor"
16         };
18         Ext.Viewport.add([notesListContainer,noteEditor]);
19     }
20 });

Ready to check it out? Well, start the emulator. :-)

A tap on the New Button should render the Note Editor View:

Editing A Record Rendered In A Sencha Touch List

We also want to activate the Note Editor View when a note’s disclosure button is tapped:

In order to accomplish this, we need to revisit the onEditNoteCommand() function in the Controller, and add the code that will activate the NoteEditor:

1 onEditNoteCommand: function (list, record) {
3     console.log("onEditNoteCommand");
5     this.activateNoteEditor(record);
6 }

Incredibly simple thanks to the fact that the disclose event supplies the selected Note model instance to the handler through the record argument. All we need to do here is call activateNoteEditor(), which we created a few minutes ago.

Back in the emulator, we should be able to see the Note Editor render the selected note:

Now it is time to save the note. We need to take care of a few things in order for this to happen.

Using A LocalStorage Proxy In Sencha Touch

First, we need to stop using hard-coded notes as the data for the Notes store.

Up to this point, we have been using the data config to define a few hard-coded records in the store:

1 Ext.define("", {
2     extend: "",
3     config: {
4         model: "NotesApp.model.Note",
5         data: [
6             { title: "Note 1", narrative: "narrative 1" },
7             { title: "Note 2", narrative: "narrative 2" },
8             { title: "Note 3", narrative: "narrative 3" },
9             { title: "Note 4", narrative: "narrative 4" },
10             { title: "Note 5", narrative: "narrative 5" },
11             { title: "Note 6", narrative: "narrative 6" }
12         ],
13         sorters: [{ property: 'dateCreated', direction: 'DESC'}]
14     }
15 });

As we intend to cache notes on the device that runs the app, we are going to discontinue the data config in the store, and define a LocalStorage proxy as follows:

1 Ext.define("", {
2     extend: "",
3     requires:"",
4     config: {
5         model: "NotesApp.model.Note",
6         proxy: {
7             type: 'localstorage',
8             id: 'notes-app-store'
9         },
10         sorters: [{ property: 'dateCreated', direction: 'DESC'}]
11     }
12 });

LocalStorageProxy uses the HTML5 localStorage API to save Model data on the client browser. This proxy is ideal for storing multiple records of similar data. And it requires that we provide the id config, which is the key that will identify our data in the localStorage object.

Now the Notes store has the ability to save and read data from localStorage, and we can go back to the Views and Controller to take care of the functions that will save the data.

Adding Event Listeners To A Sencha Touch Controller

In the NoteEditor Class, let’s modify the saveButton declaration in the initialize() function like so:

1 var saveButton = {
2     xtype: "button",
3     ui: "action",
4     text: "Save",
5     handler: this.onSaveButtonTap,
6     scope: this
7 };

The handler config defines the handler function that will run when a user taps the button. To make sure we run the handler in the scope of the NoteEditor, we set the scope config to this.

Now we can define onSaveButtonTap() as follows:

1 onSaveButtonTap: function () {
2     console.log("saveNoteCommand");
3     this.fireEvent("saveNoteCommand", this);
4 }

No surprises here, right? As we’ve done with other handlers, we are capturing the Button tap event within the View and defining a View event, saveNoteCommand.

As we already know, the fact that the NoteEditor View broadcasts the saveNoteCommand event is not enough for the Controller to be able to listen to it. We need to tell the Controller where this event is coming from, which we did when we added the noteEditor entry in the refs config of the Controller:

1 refs: {
2     // We're going to lookup our views by xtype.
3     notesListContainer: "noteslistcontainer",
4     noteEditor: "noteeditor"
5 }

We will use the Controller’s control config to map the saveNoteCommand event to a handler function. Therefore, need an entry for the Note Editor in the control config:

1 control: {
2     notesListContainer: {
3         // The commands fired by the notes list container.
4         newNoteCommand: "onNewNoteCommand",
5         editNoteCommand: "onEditNoteCommand"
6     },
7     noteEditor: {
8         // The commands fired by the note editor.
9         saveNoteCommand: "onSaveNoteCommand"
10     }
11 }

Finally, we will define the onSaveNoteCommand() function like so:

1 onSaveNoteCommand: function () {
3     console.log("onSaveNoteCommand");
5     var noteEditor = this.getNoteEditor();
7     var currentNote = noteEditor.getRecord();
8     var newValues = noteEditor.getValues();
10     // Update the current note's fields with form values.
11     currentNote.set("title", newValues.title);
12     currentNote.set("narrative", newValues.narrative);
14     var errors = currentNote.validate();
16     if (!errors.isValid()) {
17         Ext.Msg.alert('Wait!', errors.getByField("title")[0].getMessage(), Ext.emptyFn);
18         currentNote.reject();
19         return;
20     }
22     var notesStore = Ext.getStore("Notes");
24     if (null == notesStore.findRecord('id', {
25         notesStore.add(currentNote);
26     }
28     notesStore.sync();
30     notesStore.sort([{ property: 'dateCreated', direction: 'DESC'}]);
32     this.activateNotesList();
33 }

We begin onSaveNoteCommand() acquiring references to the note being edited and the values in the form’s fields:

1 var noteEditor = this.getNoteEditor();
2 var currentNote = noteEditor.getRecord();
3 var newValues = noteEditor.getValues();

Then, we transfer the new values to the loaded note:

1 currentNote.set("title", newValues.title);
2 currentNote.set("narrative", newValues.narrative);

Model Validation In Sencha Touch

Next comes an important part, which is validation. To validate the new values we loaded into the model instance, we first call the model’s validate() function, and then call the isValid() function on the errors object returned by validate():

1 var errors = currentNote.validate();
3 if (!errors.isValid()) {
4     Ext.Msg.alert('Wait!', errors.getByField("title")[0].getMessage(), Ext.emptyFn);
5     currentNote.reject();
6     return;
7 }

The’s validate() function iterates over the validations defined for the model, and returns an instance containing instances for each model field that is invalid.

In our case, the only field with an attached validator is the note’s title. When we find that the model is invalid, we first display an alert using the validator’s configured message, and then call the model’s reject() function. This function reverts the modified fields back to their original values before we exit the onSaveNoteCommand() handler.

Saving Data Using LocalStorageProxy

In onSaveNoteCommand(), after confirming that the modified note is valid, we move on to save it on the device:

1 var notesStore = Ext.getStore("Notes");
3 if (null == notesStore.findRecord('id', {
4     notesStore.add(currentNote);
5 }
7 notesStore.sync();

As this routine works for new or edited notes, we need to find out if the note is new by searching the store using its findRecrod() function. If the note is new, we add it to the store.

The store’s sync() function asks the store’s proxy to process all the changes, effectively saving new or edited notes, and removing deleting notes from localStorage.

After the store’s records have been updated, we sort them by date:

1 notesStore.sort([{ property: 'dateCreated', direction: 'DESC'}]);

Returning To The Main View

Our last step in onSaveNoteCommand() consists of invoking the activateNotesList() function. This is a helper function, similar to activateNoteEditor(), that will make the app’s main View active:

1 activateNotesList: function () {
2     Ext.Viewport.animateActiveItem(this.getNotesListContainer(), this.slideRightTransition);
3 }

In this case we are using a right-slide transition, which we will define like so:

1 slideRightTransition: { type: 'slide', direction: 'right' }

OK. What do you think about doing another quick check? This time we should be able to save a note:


In this article we added a couple of features to the Notes App: the ability to create notes, and edit existing notes.

We started by learning how to use Sencha Touch’s Form components to edit data in an application, and how to use a LocalStorageProxy instance to cache data on the device running the application. We also learned how to validate a Sencha Touch data Model, synchronize a Data Store with its Proxy, and revert Model changes when its data is invalid.

In addition, we learned how to create transitions and connect different Views in a multi-view application.

At this point the application is missing the ability to delete notes. We will add this feature in the next part of this tutorial, where we will also modify the Notes List so it renders the cached notes grouped by date.

Stay tuned!


Download the source code for this article:

The Entire Series