PHP Class for Ext Form Remote Validation
在Ext JS中,Form里面的数据,同样可以直接提交给Server,在Server端完成数据校验和存储。这个过程,在Ext JS API文档中,对应着Ext.form.Action.Submit。同样,也可以通过Ext.form.BasicForm.submit()来调用。
Submit的基本参数,包括:url,指定提交目的地,比如./mydata.php;waitMsg,数据提交过程中的等待信息;success,数据提交成功后的处理过程,比如关闭Form对话框、更新客户端列表等等。
Ext JS对于数据提交,使用的是标准的POST方式;Server端在接受到提交的数据之后,进行校验,然后将结果,使用JSON数据格式,返回给Ext Form。从Ext.form.Action.Submit这个文档,可以看出,Ext Form对数据校验结果的要求,同样包括两部分,一是success状态,true或false;二是errors块,这个errors块列出了哪些field,有哪些类型的错误。文档的例子如下:
1: {2: success: false,
3: errors: {4: clientCode: "Client not found",
5: portOfLoading: "This field must not be null"
6: } 7: }Ext Form收到数据校验结果之后,如果校验成功,会转向执行success所定义的过程;如果校验失败,Ext Form会以相应的方式,显示校验结果中所包含的出错信息。
同Load一样,对于实际的应用来讲,Ext Form这一端没什么特别要求,只是多定义一个success所对应的过程。重要的还是Server端,如何进行数据校验。这里同样给出一个PHP Class,ExtSubmitResponse,以方便数据校验工作的完成。
1: class ExtSubmitResponse extends stdClass {
2: public $success;
3: public $errors;
4: 5: function __construct() {
6: $this->success = true;
7: $this->errors = null;
8: } 9: 10: function pushError( $field, $errorMsg ) {
11: if( $this->success ) {
12: $this->success = false;
13: $this->errors = new stdClass();
14: } 15: 16: $this->errors->$field = $errorMsg; 17: } 18: 19: function getMessage() {
20: return json_encode( $this );
21: } 22: }具体的使用方法,如下:
1: // initial a instance
2: $extResponse = new ExtSubmitResponse();
3: ...4: // push the error
5: $extResponse->pushError('clientName','Client not found');
6: $extResponse->pushError('clientLicense', 'You must accept this license.');
7: ...8: // response to Ext Form
9: echo $extResponse->getMessage();
需要强调的是,Ext Form的数据是POST过来的,并没有传送JSON格式的数据。如果提交的数据,通过了校验,Server也应该传送success消息,并保存数据。

