Bryan P
Bryan P

Reputation: 5051

Prevent server handler from firing

Can we stop a server handler from firing if a client handler (on the same widget) meets a validation condition? UI

I don't want Submit to perform any server function if the text box is empty.

function doGet() {
  var app = UiApp.createApplication();
  var flex = app.createFlexTable()
     .setWidget(0, 0, app.createTextBox().setId('textbox'))
     .setWidget(0, 1, app.createButton('Submit').setId('submit'))
     .setWidget(0, 2, app.createLabel().setId('status'));

  var clientHandler = app.createClientHandler().validateNotMatches(app.getElementById('textbox'), ' ');

  var serverHandler = app.createServerHandler('submit').addCallbackElement(flex);

  app.getElementById('submit').addClickHandler(clientHandler).addClickHandler(serverHandler);

  app.add(flex);
  return app;

}

function submit(e) {
  var app = UiApp.getActiveApplication();
  app.getElementById('status').setText('Server handler fired');
  return app;
}

Upvotes: 0

Views: 371

Answers (1)

Corey G
Corey G

Reputation: 7858

You don't need or want a client handler here, just a validator on the server handler:

function doGet() {
  var app = UiApp.createApplication();
  var flex = app.createFlexTable()
     .setWidget(0, 0, app.createTextBox().setId('textbox'))
     .setWidget(0, 1, app.createButton('Submit').setId('submit'))
     .setWidget(0, 2, app.createLabel().setId('status'));

  var serverHandler = app.createServerHandler('submit')
     .validateLength(app.getElementById('textbox'), 1, null)
     .addCallbackElement(flex);

  app.getElementById('submit').addClickHandler(serverHandler);

  app.add(flex);
  return app;

}

function submit(e) {
  var app = UiApp.getActiveApplication();
  app.getElementById('status').setText('Server handler fired');
  return app;
}

If you want a message explaining what went wrong, you can add this:

var clientHandler = app.createClientHandler()
    .validateNotLength(app.getElementById('textbox'), 1, null)
    .forTargets(app.getElementById('status'))
    .setText('Cannot be empty');

app.getElementById('submit').addClickHandler(serverHandler)
    .addClickHandler(clientHandler);

Upvotes: 2

Related Questions