Implement CRUD Operation in Ext JS 4 Form - Part 2:

We created Student Master form and implemented Read operation in the previous chapter. In this chapter, we will implement create, update and delete operations using Model class in the Student Master form.

Following code example shows create operation:

   onCreateClick: function () {
        var studentModel = Ext.create('School.model.Student');

        studentModel.set(stdMaster.getValues());

        studentModel.save({
            scope: this, //controller would be accessible inside load
            success: function (record, operation) { //do something if the load succeeded
                try {
                    this.getStudentMasterForm().loadRecord(record);
                    Ext.Msg.alert('Status', 'Student Saved Successfully!');
                }
                catch (ex) {
                    Ext.Msg.alert('Status', 'Invalid data in server response: ' + ex.Message);
                }
            },
            failure: function (record, operation) {
                Ext.Msg.alert('Status', 'Service request faild.');
            }
        });
    }

As you can see in the above code snippet, we have used save() method to save new student data. You can also update data in the same way.

Following code example shows how you can delete the record using destroy() method of Model class:

    onDeleteClick: function () {
        var studentModel = stdMaster.getRecord();
 
        studentModel.destroy({
            scope: this, //controller would be accessible inside load
            failure: function (record, operation) {
                Ext.Msg.alert('Status', 'Service request faild.');
            },
            success: function (record, operation) {
                try {
                    var resp = Ext.decode(operation.response.responseText);
                    if (resp.success) { // check if delete succeded at server side
                        this.getStudentMasterForm().clearForm();
                    }
                }
                catch (ex) {
                    Ext.Msg.alert('Status', 'Exception: ' + ex.Message);
                }
            }
        });
    }

Visit Sencha Documentation for more information on load, save and destroy methods of model.

Response from the server should look like below:

    {
        "message":"message from the server",
        "success":true or false,
        "data":[{"Id":1,"address1":"","address2":"","birthDate":null,"city":"","firstName":"","lastName":"","middleName":"","state":""}]
    }

message: string message returned from the service
success: Boolean to indicate whether operation was executed successfully at server side or not.
data: model data returned from the service.

So this way you can implement CRUD operation in ExtJS 4 form.


Live Example