dbgenerate.js
[app.Builder.js] / dbgenerate.js
1 //<script type="text/javascript">
2
3 /**
4  * This is a hacky generator to generate element definitions for the Roo version from the database
5  * 
6  * Let's see if libgda can be used to generate our Readers for roo...
7  * 
8  * Concept - conect to database..
9  * 
10  * list tables
11  * 
12  * extra schemas..
13  * 
14  * write readers..
15  * 
16  * usage: seed generate.js
17  *
18  *
19  *
20  *
21  *Hack needed to latest GLib-2.0.gir 
22  *
23  * <record name="KeyFile" c:type="GKeyFile" disguised="1">
24         <constructor name="new" c:identifier="g_key_file_new">
25         <return-value transfer-ownership="full">
26           <type name="KeyFile" c:type="GKeyFile*"/>
27         </return-value>
28       </constructor>
29  *
30  *
31  * remove introspectable =0 from g_key_file_get_groups
32  *   and add transfer-owneership = none to return value
33  * remove introspectable =0 from g_key_file_get_keys
34  *   and add transfer-owneership = none to return value* 
35  * 
36  */
37 Gda  = imports.gi.Gda;
38 GObject = imports.gi.GObject;
39
40 GLib = imports.gi.GLib;
41
42 console = imports.console;
43 File = imports.File.File;
44 Options = imports.Options.Options;
45
46 //Gda.init();
47
48 var prov = Gda.Config.list_providers ();
49 //print(prov.dump_as_string());
50
51 var o = new Options({
52     help_description : 'Element builder for App Builder based on database schema',
53     
54     options:  [
55         { arg_long : 'DBTYPE' , arg_short : 't', description : 'Database Type (eg. MySQL or PostgreSQL ' },
56         { arg_long : 'DBNAME' , arg_short : 'd', description : 'Database Name' },
57         { arg_long : 'USERNAME' , arg_short : 'u', description : 'Username'},
58         { arg_long : 'PASSWORD' , arg_short : 'p', description : 'Password' , arg_default :'' },
59         { arg_long : 'INI' , arg_short : 'I', description :
60                     'Either base directory which has Pman/***/DataObjects/***.links.ini or location of ini file.' },
61     ]
62            
63 })
64
65
66
67 var cfg = o.parse(Seed.argv);
68 print(JSON.stringify(cfg, null,4));
69
70 var   cnc = Gda.Connection.open_from_string (cfg.DBTYPE,
71          "DB_NAME=" + cfg.DBNAME, 
72         "USERNAME=" + cfg.USERNAME + ';PASSWORD=' + cfg.PASSWORD,
73         Gda.ConnectionOptions.NONE, null);
74
75
76
77                                               
78
79  
80 Gda.DataSelect.prototype.fetchAll = function()
81 {
82     var cols = [];
83     
84     for (var i =0;i < this.get_n_columns(); i++) {
85         cols.push(this.get_column_name(i));
86     }
87     //print(JSON.stringify(cols, null,4));
88     var iter = this.create_iter();
89     var res = [];
90     //print(this.get_n_rows());
91     var _this = this;
92     for (var r = 0; r < this.get_n_rows(); r++) {
93         
94         // single clo..
95         //print("GOT ROW");
96         if (cols.length == 1) {
97             res.push(this.get_value_at(0,r).get_string());
98             continue;
99         }
100         var add = { };
101         
102         cols.forEach(function(n,i) {
103             var val = _this.get_value_at(i,r);
104             var type = GObject.type_name(val.g_type) ;
105             var vs = ['GdaBinary', 'GdaBlob' ].indexOf(type) > -1 ? val.value.to_string(1024) : val.value;
106             //print(n + " : TYPE: " + GObject.type_name(val.g_type) + " : " + vs);
107             //print (n + '=' + iter.get_value_at(i).value);
108             add[n] = vs;
109         });
110         
111         res.push(add);
112         
113     }
114     return res;
115
116 }
117
118 var map = {
119     'date' : 'date',
120     'datetime' : 'date',
121     'timestamp with time zone' : 'date',
122     'timestamp without time zone' : 'date',
123     'time' : 'string', //bogus
124     'int' : 'int',
125     'integer' : 'int',
126     'bigint' : 'int',
127     'double' : 'float',
128     'tinyint' : 'int',
129     'smallint' : 'int',
130     'decimal' : 'float',
131     'float' : 'float',
132     'numeric' : 'float',
133     'char' : 'string',
134     'character' : 'string',
135     'character varying' : 'string',
136     'varchar' : 'string',
137     'text' : 'string',
138     'longtext' : 'string',
139     'tinytext' : 'string',
140     'mediumtext' : 'string',
141     'enum' : 'string',
142     'timestamp' : 'number',
143     'blob' : 'text',
144     'bytea' : 'text',
145     'boolean' : 'int',
146     'text[]' : 'string',
147     
148 }
149
150 var ini = { }
151
152 function readIni(fn)
153 {
154     print('Read INI : ' + fn);
155     var key_file = new GLib.KeyFile.c_new();
156     if (!key_file.load_from_file (fn , GLib.KeyFileFlags.NONE )) {
157         return;
158     }
159    
160     var groups = key_file.get_groups();
161     groups.forEach(function(g) {
162         ini[g] = {}
163         print("KEY:"+g);
164         var keys = key_file.get_keys(g);
165         if (!keys) { return; }
166        
167         keys.forEach(function(k) {
168                 ini[g][k] = key_file.get_value(g,k);
169         })
170     })
171     
172 }
173  print("DONE KEYS");
174 if (File.isFile(cfg.INI)) {
175     if (cfg.INI.match(/links\.ini$/)) {
176         readIni(cfg.INI);
177     } else {
178         readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
179     }
180 }
181
182
183 if (File.isDirectory(cfg.INI)) {
184         
185
186     //--- load ini files..
187     // this is very specific.
188     
189     var dirs = File.list( cfg.INI + '/Pman').filter( 
190         function(e) { 
191             if (!File.isDirectory(cfg.INI + '/Pman/' + e + '/DataObjects')) {
192                 return false;
193             }
194             return true;
195         }
196     );
197     
198      
199     dirs.forEach(function(d) {
200         // this currently misses the web.*/Pman/XXXX/DataObjects..
201         var path = cfg.INI + '/Pman/' + d + '/DataObjects';
202          
203         if (!File.isDirectory(path)) {
204             return; //skip
205         }
206         var inis = File.list(path).filter(
207             function(e) { return e.match(/\.links\.ini$/); }
208         );
209         if (!inis.length) {
210             return;
211         }
212         
213         inis.forEach(function(i) {
214             readIni(path + '/' + i); 
215             
216         })
217  
218     });
219     // look at web.XXXX/Pman/XXX/DataObjects/*.ini
220     var inis = File.list(cfg.INI).filter(
221         function(e) { return e.match(/\.links\.ini$/); }
222     )
223     
224      inis.forEach(function(i) {
225         readIni(path + '/' + i); 
226         
227     })
228     
229     
230 }
231 //print(JSON.stringify(ini, null,4));
232  //console.dump(ini);
233
234
235  //Seed.quit();
236
237 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
238
239
240 switch(cfg.DBTYPE) {
241     case "MySQL":
242         query_tables = "SHOW TABLES";
243         query_describe_table = "DESCRIBE `%s`";
244         break;
245     
246     case 'PostgreSQL':
247         query_tables = "select c.relname FROM pg_catalog.pg_class c " + 
248             "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + 
249             "WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast')" +
250             "AND pg_catalog.pg_table_is_visible(c.oid) ";
251          query_describe_table =  
252                 "SELECT " +
253                 "f.attnum AS number, " +
254                 "f.attname AS Field, " +
255                 "f.attnum, " +
256                 "CASE WHEN f.attnotnull = 't' THEN 'NO' ELSE 'YES' END AS isNull, " + 
257                 "pg_catalog.format_type(f.atttypid,f.atttypmod) AS Type, " +
258                 "CASE WHEN p.contype = 'p' THEN 't' ELSE 'f' END AS primarykey, " +
259                 "CASE WHEN p.contype = 'u' THEN 't' ELSE 'f' END AS uniquekey, " +
260                 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
261                 "CASE WHEN p.contype = 'f' THEN p.confkey END AS foreignkey_fieldnum, " +
262                 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
263                 "CASE WHEN p.contype = 'f' THEN p.conkey END AS foreignkey_connnum, " +
264                 "CASE WHEN f.atthasdef = 't' THEN d.adsrc END AS default " +
265                 "FROM pg_attribute f JOIN pg_class c ON c.oid = f.attrelid " +
266                 "        JOIN pg_type t ON t.oid = f.atttypid " +
267                 "        LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum " +
268                 "        LEFT JOIN pg_namespace n ON n.oid = c.relnamespace " +
269                 "        LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY ( p.conkey ) " +
270                 "        LEFT JOIN pg_class AS g ON p.confrelid = g.oid " +
271                 "WHERE c.relkind = 'r'::char AND n.nspname = '%n' " +
272                 "AND c.relname = '%s' AND f.attnum > 0 ORDER BY number";
273                 
274                 
275                 
276         break;
277     default:
278         throw "Invalid data base type " + cfg.DBTYPE + " should be MySQL or PostgreSQL";
279 /*
280            "Field": "province",
281         "Type": "varchar(255)",
282         "Null": "NO", << or is null
283         "Key": null,
284         "Default": null,
285         "Extra": 
286 */  
287 }
288
289
290  
291
292 var tables = cnc.execute_select_command( query_tables).fetchAll();
293 print(JSON.stringify(tables));
294
295 var readers = [];
296 tables.forEach(function(table) {
297     //print(table);
298     var schema = cnc.execute_select_command(
299             query_describe_table.replace(/%s/, table).replace(/%n/,'public')
300             ).fetchAll();
301     
302     
303     var reader = []; 
304     var colmodel = []; 
305     var combofields= [ { name : 'id', type: 'int' } ]; // technically the primary key..
306          
307     var form = {}
308        
309     var firstTxtCol = '';
310     
311     //print(JSON.stringify(schema, null,4));    Seed.quit();
312     
313     schema.forEach(function(e)  {
314         e.Type = e.Type || e.type;
315         e.Field = e.Field || e.field;
316          
317         var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
318         var row  = { }; 
319         if (type) {
320             e.Type = type[1];
321             e.Size = type[2];
322         }
323         
324         
325         
326         row.name = e.Field;
327         
328         
329         if (typeof(map[e.Type]) == 'undefined') {
330            console.dump(e);
331            throw {
332                 name: "ArgumentError", 
333                 message: "Unknown mapping for type : " + e.Type
334             };
335         }
336         row.type = map[e.Type];
337         
338         if (row.type == 'string' && !firstTxtCol.length) {
339             firstTxtCol = row.name;
340         }
341         
342         if (row.type == 'date') {
343             row.dateFormat = 'Y-m-d';
344         }
345         reader.push(row);
346         
347         if (combofields.length == 1 && row.type == 'string') {
348             combofields.push(row);
349         }
350         
351         
352         var title = row.name.replace(/_id/, '').replace(/_/g, ' ');
353         title  = title[0].toUpperCase() + title.substring(1);
354         
355         colmodel.push({
356             "xtype": "ColumnModel",
357             "header": title,
358             "width":  row.type == 'string' ? 200 : 75,
359             "dataIndex": row.name,
360             "|renderer": row.type != 'date' ? 
361                     "function(v) { return String.format('{0}', v); }" :
362                     "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
363             "|xns": "Roo.grid",
364             "*prop": "colModel[]"
365         });
366         var xtype = 'TextField';
367         
368         
369         if (row.type == 'number') {
370             xtype = 'NumberField';
371         }
372         if (row.type == 'date') {
373             xtype = 'DateField';
374         }
375         if (e.Type == 'text') {
376             xtype = 'TextArea';
377         }
378         if (row.name == 'id') {
379             xtype = 'Hidden';
380         } 
381         // what about booleans.. -> checkboxes..
382         
383         
384         
385         form[row.name] = {
386             fieldLabel : title,
387             name : row.name,
388             width : row.type == 'string' ? 200 : 75,
389             '|xns' : 'Roo.form',
390             xtype : xtype
391         }
392          if (xtype == 'DateField') {
393             form[row.name].format = 'Y-m-d';
394             form[row.name].width = 100;
395         }
396         
397         if (xtype == 'TextArea') {
398             form[row.name].height = 100;
399         }
400         if (xtype == 'Hidden') {
401             delete form[row.name].fieldLabel;
402             delete form[row.name].width;
403         }
404         
405     });
406     
407     var combo = {
408         '|xns' : 'Roo.form',
409         xtype: 'ComboBox',
410         allowBlank : false,
411         editable : false,
412         emptyText : 'Select ' + table,
413         forceSelection : true,
414         listWidth : 400,
415         loadingText: 'Searching...',
416         minChars : 2,
417         pageSize : 20,
418         qtip: 'Select ' + table,
419         selectOnFocus: true,
420         triggerAction : 'all',
421         typeAhead: true,
422         
423         width: 300,
424         
425         
426         
427         tpl : '<div class="x-grid-cell-text x-btn button"><b>{name}</b> </div>', // SET WHEN USED
428         queryParam : '',// SET WHEN USED
429         fieldLabel : table,  // SET WHEN USED
430         valueField : 'id',
431         displayField : '', // SET WHEN USED eg. project_id_name
432         hiddenName : '', // SET WHEN USED eg. project_id
433         name : '', // SET WHEN USED eg. project_id_name
434         items : [
435             {
436                     
437                 '*prop' : 'store',
438                 'xtype' : 'Store',
439                 '|xns' : 'Roo.data',
440                 'remoteSort' : true,
441                 '|sortInfo' : '{ direction : \'ASC\', field: \'id\' }',
442                 listeners : {
443                     '|beforeload' : 'function (_self, o)' +
444                     "{\n" +
445                     "    o.params = o.params || {};\n" +
446                     "    // set more here\n" +
447                     "}\n"
448                 },
449                 items : [
450                     {
451                         '*prop' : 'proxy',
452                         'xtype' : 'HttpProxy',
453                         'method' : 'GET',
454                         '|xns' : 'Roo.data',
455                         '|url' : "baseURL + '/Roo/" + table + ".php'",
456                     },
457                     
458                     {
459                         '*prop' : 'reader',
460                         'xtype' : 'JsonReader',
461                         '|xns' : 'Roo.data',
462                         'id' : 'id',
463                         'root' : 'data',
464                         'totalProperty' : 'total',
465                         '|fields' : JSON.stringify(combofields)
466                         
467                     }
468                 ]
469             }
470         ]
471     }
472     
473     
474     
475     
476     //print(JSON.stringify(reader,null,4));
477     readers.push({
478         table : table ,
479         combo : combo,
480         combofields : combofields,
481         reader :  reader,
482         oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
483         colmodel : colmodel,
484         firstTxtCol : firstTxtCol,
485         form : form
486     });
487     
488     //console.dump(schema );
489     
490      
491 });
492
493
494
495 // merge in the linked tables..
496 readers.forEach(function(reader) {
497     if (typeof(ini[reader.table]) == 'undefined') {
498      
499         return;
500     }
501     print("OVERLAY - " + reader.table);
502     // we have a map..
503     for (var col in ini[reader.table]) {
504         var kv = ini[reader.table][col].split(':');
505         
506         
507         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
508         if (!add) {
509             continue;
510         }
511         // merge in data (eg. project_id => project_id_*****
512      
513         add.oreader.forEach(function(or) {
514             reader.reader.push({
515                 name : col + '_' + or.name,
516                 type : or.type
517             });
518         });
519         
520         // col is mapped to something..
521         var combofields = add.combofields;
522         if (add.combofields.length < 2) {
523             continue;
524         }
525         if (typeof(reader.form[col]) == 'undefined') {
526             print (JSON.stringify(reader.form, null,4));
527             print("missing linked column " + col);
528             continue;
529         }
530         
531         var combofields_name = add.combofields[1].name;
532         var old =   reader.form[col];
533         reader.form[col] = JSON.parse(JSON.stringify(add.combo)); // clone
534         reader.form[col].queryParam  = 'query[' + combofields_name + ']';// SET WHEN USED
535         reader.form[col].fieldLabel = old.fieldLabel;  // SET WHEN USED
536         reader.form[col].hiddenName = old.name; // SET WHEN USED eg. project_id
537         reader.form[col].displayField = combofields_name; // SET WHEN USED eg. project_id
538         reader.form[col].name  = old.name + '_' + combofields_name; // SET WHEN USED eg. project_id_name
539         reader.form[col].tpl = '<div class="x-grid-cell-text x-btn button"><b>{' + combofields_name +'}</b> </div>'; // SET WHEN USED
540         
541              
542     };
543     
544     
545 });
546
547 //readers.forEach(function(reader) {
548 //    delete reader.oreader;
549 //});
550
551  
552
553
554
555 //print(JSON.stringify(readers, null, 4));
556
557 readers.forEach(function(reader) {
558     
559
560     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
561     if (!File.isDirectory(dir)) {
562         print("mkdir " + dir);
563         File.mkdir(dir);
564     }
565     
566     // READERS
567     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
568     
569                 
570     var jreader = {
571         '|xns' : 'Roo.data',
572         xtype : "JsonReader",
573         totalProperty : "total",
574         root : "data",
575         '*prop' : "reader",
576         id : 'id', // maybe no..
577        
578         '|fields' :  JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
579     };
580     
581     File.write(
582         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
583         JSON.stringify(jreader, null, 4)
584     )
585     
586     
587     // GRIDS
588     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
589     if (!File.isDirectory(dir)) {
590         print("mkdir " + dir);
591         File.mkdir(dir);
592     }
593     
594
595     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
596     
597     File.write(
598         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
599             
600        
601         JSON.stringify({
602             '|xns' : 'Roo',
603             xtype : "GridPanel",
604             "title": reader.table,
605             "fitToframe": true,
606             "fitContainer": true,
607             "tableName": reader.table,
608             "background": true,
609             "region" : 'center',
610             "listeners": {
611                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
612             },
613             "items": [
614                 {
615                     "*prop": "grid",
616                     "xtype": "Grid",
617                     "autoExpandColumn": reader.firstTxtCol,
618                     "loadMask": true,
619                     "listeners": {
620                         "|render": "function() \n" +
621                             "{\n" +
622                             "    _this.grid = this; \n" +
623                             "    //_this.dialog = Pman.Dialog.FILL_IN\n" +
624                             "    if (_this.panel.active) {\n" +
625                             "       this.footer.onClick('first');\n" +
626                             "    }\n" +
627                             "}",
628                         "|rowdblclick": "function (_self, rowIndex, e)\n" + 
629                             "{\n" + 
630                             "    if (!_this.dialog) return;\n" + 
631                             "    _this.dialog.show( this.getDataSource().getAt(rowIndex).data, function() {\n" + 
632                             "        _this.grid.footer.onClick('first');\n" + 
633                             "    }); \n" + 
634                             "}\n"
635                     },
636                     "|xns": "Roo.grid",
637
638                     "items": [
639                         {
640                             "*prop": "dataSource",
641                             "xtype": "Store",
642                              remoteSort : true,
643                             '|sortInfo' : "{ field : '" + reader.firstTxtCol  +  "', direction: 'ASC' }", 
644                             "|xns": "Roo.data",
645                             "items": [
646                                 
647                                 {
648                                     "*prop": "proxy",
649                                     "xtype": "HttpProxy",
650                                     "method": "GET",
651                                     "|url": "baseURL + '/Roo/" + reader.table + ".php'",
652                                     "|xns": "Roo.data"
653                                 },
654                                 jreader
655                             ]
656                         },
657                         {
658                             "*prop": "footer",
659                             "xtype": "PagingToolbar",
660                             "pageSize": 25,
661                             "displayInfo": true,
662                             "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
663                             "emptyMsg": "No " + reader.table + " found",
664                             "|xns": "Roo"
665                         },
666                         {
667                             "*prop": "toolbar",
668                             "xtype": "Toolbar",
669                             "|xns": "Roo",
670                             "items": [
671                                 {
672                                     "text": "Add",
673                                     "xtype": "Button",
674                                     "cls": "x-btn-text-icon",
675                                     "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
676                                     "listeners": {
677                                         "|click": "function()\n"+
678                                             "{\n"+
679                                             "    if (!_this.dialog) return;\n" +
680                                             "    _this.dialog.show( { id : 0 } , function() {\n"+
681                                             "        _this.grid.footer.onClick('first');\n"+
682                                             "   }); \n"+
683                                             "}\n"
684                                     },
685                                     "|xns": "Roo.Toolbar"
686                                 },
687                                 {
688                                     "text": "Edit",
689                                     "xtype": "Button",
690                                     "cls": "x-btn-text-icon",
691                                     "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
692                                     "listeners": {
693                                         "|click": "function()\n"+
694                                             "{\n"+
695                                             "    var s = _this.grid.getSelectionModel().getSelections();\n"+
696                                             "    if (!s.length || (s.length > 1))  {\n"+
697                                             "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
698                                             "        return;\n"+
699                                             "    }\n"+
700                                             "    if (!_this.dialog) return;\n" +
701                                             "    _this.dialog.show(s[0].data, function() {\n"+
702                                             "        _this.grid.footer.onClick('first');\n"+
703                                             "    }); \n"+
704                                             "    \n"+
705                                             "}\n" 
706                                         
707                                     },
708                                     "|xns": "Roo.Toolbar"
709                                 },
710                                 {
711                                     "text": "Delete",
712                                     "cls": "x-btn-text-icon",
713                                     "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
714                                     "xtype": "Button",
715                                     "listeners": {
716                                         "|click": "function()\n"+
717                                             "{\n"+
718                                             "     Pman.genericDelete(_this, '" + reader.table + "'); \n"+
719                                             "}\n"+
720                                             "        "
721                                     },
722                                     "|xns": "Roo.Toolbar"
723                                 }
724                             ]
725                         }, // end toolbar
726                     ].concat( reader.colmodel)
727                 }
728             ]
729             
730             
731         }, null, 4)
732     )
733     
734     /// FORMS..
735     
736     dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form'; 
737     if (!File.isDirectory(dir)) {
738         print("mkdir " + dir);
739         File.mkdir(dir);
740     }
741     var formElements = [];
742     var formHeight = 50;
743     for (var k in reader.form) {
744         if (k == 'id') { // should really do primary key testing..
745             continue;
746         }
747         formHeight += reader.form[k].xtype == 'TextArea' ? 100 : 30;
748         
749         formElements.push(reader.form[k]);
750     }
751     if (reader.form['id']) {
752         formElements.push(reader.form['id']);
753     }
754     
755
756     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
757     var frmCfg = 
758     {
759         '|xns' : 'Roo.form',
760         xtype : "Form",
761         listeners : {
762             "|actioncomplete" : "function(_self,action)\n"+
763                 "{\n"+
764                 "    if (action.type == 'setdata') {\n"+
765                 "       //_this.dialog.el.mask(\"Loading\");\n"+
766                 "       //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
767                 "       return;\n"+
768                 "    }\n"+
769                 "    if (action.type == 'load') {\n"+
770                 "        _this.dialog.el.unmask();\n"+
771                 "        return;\n"+
772                 "    }\n"+
773                 "    if (action.type =='submit') {\n"+
774                 "    \n"+
775                 "        _this.dialog.el.unmask();\n"+
776                 "        _this.dialog.hide();\n"+
777                 "    \n"+
778                 "         if (_this.callback) {\n"+
779                 "            _this.callback.call(_this, _this.form.getValues());\n"+
780                 "         }\n"+
781                 "         _this.form.reset();\n"+
782                 "         return;\n"+
783                 "    }\n"+
784                 "}\n",
785             
786             "|rendered" : "function (form)\n"+
787                 "{\n"+
788                 "    _this.form= form;\n"+
789                 "}\n"
790         },
791         method : "POST",
792         style : "margin:10px;",
793         "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
794         items : formElements
795     };
796     
797     
798     File.write(
799         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
800             
801        
802         JSON.stringify( frmCfg, null, 4)
803     );
804             
805             
806    
807    
808    
809      /// COMBO..
810     
811     dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox'; 
812     if (!File.isDirectory(dir)) {
813         print("mkdir " + dir);
814         File.mkdir(dir);
815     }
816    
817     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
818     
819     File.write(
820         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
821             
822        
823         JSON.stringify(reader.combo, null, 4)
824     );
825             
826    
827    
828    
829    
830    
831     // DIALOG.
832    
833    
834     dir = GLib.get_home_dir() + '/.Builder/Roo.LayoutDialog'; 
835     if (!File.isDirectory(dir)) {
836         print("mkdir " + dir);
837         File.mkdir(dir);
838     }
839     var formElements = [];
840     for (var k in reader.form) {
841         if (k == 'id') { // should really do primary key testing..
842             continue;
843         }
844         formElements.push(reader.form[k]);
845     }
846     formElements.push(reader.form['id']);
847
848     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
849     
850     File.write(
851         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
852             
853        
854         JSON.stringify({
855        
856             "closable": false,
857             "collapsible": false,
858             "height": formHeight,
859             "resizable": false,
860             "title": "Edit / Create " + reader.table,
861             "width": 400,
862             "modal" : true,
863             "xtype": "LayoutDialog",
864             "|xns": "Roo",
865             "items": [
866                 {
867                     "|xns": "Roo",
868                     "xtype": "LayoutRegion",
869                     "*prop": "center"
870                 },
871                 {
872                     "region": "center",
873                     "xtype": "ContentPanel",
874                     "|xns": "Roo",
875                     "items": [
876                         frmCfg
877                     ]
878                 },
879                 
880                 {
881                     "listeners": {
882                         "click": "function (_self, e)\n{\n    _this.dialog.hide();\n}"
883                     },
884                     "*prop": "buttons[]",
885                     "text": "Cancel",
886                     "xtype": "Button",
887                     "|xns": "Roo"
888                 },
889                 {
890                     "listeners": {
891                         "click": "function (_self, e)\n{\n    // do some checks?\n     \n    \n    _this.dialog.el.mask(\"Saving\");\n    _this.form.doAction(\"submit\");\n\n}"
892                     },
893                     "*prop": "buttons[]",
894                     "text": "Save",
895                     "xtype": "Button",
896                     "|xns": "Roo"
897                 }
898             ]
899         }, null,4)
900     );
901    
902    
903    
904 });
905
906