Search code examples
javascriptformsapostrophe-cms

apostrophe - setting data in forms-submit-widgets


I'm trying to make a contact form for people to register for events — but, the problem is, the date field in the register form needs to be populated from Google calendar every time somebody requests the page. So in trainings-forms-submit-widgets I have:

module.exports = {
  construct: function(self, options) {
    self.pageBeforeSend = function(req) {
      [all the code needed to get the info from the calendar]
    }
  }
}

Now, I can't find it anywhere - how can I populate data field in trainings-forms with the data I got? I believe in construct I need to somehow manipulate self object, but I can't find documentation on it.


Solution

  • First of all, your pageBeforeSend handler must take a callback, and it must not invoke that callback until it is actually ready.

    Second, it must add the information to a property of req.data so your page templates can see it:

    self.pageBeforeSend = function(req, callback) {
      // Let's use the request module to fetch a URL
      return request('http://some/api/somewhere', function(err, res, body) {
        if (err || response.statusCode >= 400) {
          return callback(err || response.statusCode);
        }
        // I am guessing how your API works here
        req.data.registerDate = body.registerDate;
        return callback(null);
      });
    };
    

    Second, I don't know exactly how your contact form works, as you haven't mentioned. But if you are simply outputting an HTML form of your own, you can now insert this data easily in your page template:

    <form method="POST" action="/something">
      <input name="date" value="{{ data.registerDate }}" />
    </form>
    

    If you are doing something else, such as using our apostrophe-pieces-submit-widgets module to build these forms, please clarify exactly what you're doing and I can give you more information on how to populate the field.