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