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