testcities2.erl 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. -module(testcities2).
  2. -include_lib("nitro/include/nitro.hrl").
  3. -include_lib("n4u/include/wf.hrl").
  4. %% example work with postgresql (with pool)
  5. -export([
  6. main/0,
  7. event/1
  8. ]).
  9. main() ->
  10. Tr = hm:get_tr_mod(), % get i18n module by lang
  11. Body = #dtl{file = "testcities", app = n2o_sample, bindings=[
  12. {cities, Tr:tr(testcities, cities) },
  13. {cities_show, Tr:tr(testcities, cities_show) },
  14. {cities_add, Tr:tr(testcities, cities_add) },
  15. {city_name, Tr:tr(testcities, city_name) },
  16. {city_pop, Tr:tr(testcities, city_pop) },
  17. {city_add, Tr:tr(testcities, city_add) }
  18. ]},
  19. #dtl{file = "layout", app = n2o_sample, bindings=[
  20. {page_title, Tr:tr(testcities, page_title) },
  21. {page_css, <<"<link rel=\"stylesheet\" href=\"/css/test.css\">">>},
  22. {page_body, wf:render(Body)},
  23. {page_js, <<"<script src=\"/js/testcities.js\" defer></script>">>}
  24. ]}.
  25. event(init) ->
  26. ?MODULE:event({client, {sitiesshow}});
  27. %[];
  28. event({client, {sitiesshow}}) ->
  29. Data = pq:get_all_cities(),
  30. InnerHtml = hg:generate_cities_list(Data),
  31. wf:wire(wf:f("var parent = qi('cities');"
  32. "parent.innerHTML='~s';"
  33. "window.getting_data=false;"
  34. "qi('citiesshow').disabled=false;", [unicode:characters_to_binary(InnerHtml, utf8)]));
  35. %% add one city and show all -- example with transaction
  36. event({client, {cityadd, Name, Pop}}) ->
  37. pgm:transaction(fun(Worker) ->
  38. %%epgsql:squery(Mpid, "BEGIN"), %% when transaction without pool
  39. {ok, R1} = pq:add_city_t(Worker, Name, Pop),
  40. hm:assert_int(R1),
  41. {ok, _Columns, Data} = pq:get_all_cities_t(Worker),
  42. %%hm:assert_int(R2)
  43. InnerHtml = hg:generate_cities_list(Data),
  44. wf:wire(wf:f("var parent = qi('cities');"
  45. "parent.innerHTML='~s';"
  46. "window.getting_data=false;"
  47. "qi('citiesshow').disabled=false;", [unicode:characters_to_binary(InnerHtml, utf8)])),
  48. ok
  49. %% commit pg-transaction - when transaction without pool
  50. %%epgsql:squery(Mpid, "COMMIT"),
  51. %% rollback pg-transaction - when transaction without pool
  52. %%epgsql:squery(Mpid, "ROLLBACK"),
  53. %%io:format("~p~n",[epgsql:get_cmd_status(Mpid)]),
  54. %%{ok,commit} or {ok, rollback}
  55. end);
  56. event(Event) ->
  57. wf:info(?MODULE, "Event: ~p", [Event]),
  58. ok.