View Page

Remember to check out the documentation for restdb.io Pages and for restdb.io Querying. You can also view the master template source code.


{{#inherit "layout"}}

    {{#block "head"}}
        <link href="https://websitedemo-4db9.restdb.io/assets/css/jquery.datetimepicker.min.css" rel="stylesheet">
        
        <style>
          .thank-you{
            font-size: 16px;
            padding: 20px;	
          }
        
          #webcontact-form{
            padding: 10px;
          }
          #webcontact-form input{
            width: 100%;
          }
          label{
            display: block;
          }
          .form-control{
            width: auto;
          }
          .help-block{
            margin-left:10px;
          }
          .progress{
            width: 100%;
            height:10px;
            border-radius:0px;
            margin-top: 2px;
          }
        
        </style>
    {{/block}}
    {{#block "title"}}
    <h1>Contact us</h1>
    {{/block}}
    
    {{#block "content"}}
      <p>Fill in the form, and we'll get back to you as soon as possible. This page was created with the <a href="https://restdb.io/docs/web-form-generator">Web Form Generator</a> of restdb.io. Data and files submitted from this page will end up in the "Webcontact" collection in restdb.io. A restdb.io <a href="https://restdb.io/docs/webhooks">Webhook</a> will trigger a <a target="zapier" href="https://zapier.com/zapbook/gmail">Zapier Zap</a> for Gmail and an email will be sent to us. </p>
      <div class="form-container col-md-8">
          <form role="form" id="webcontact-form">
            <div class="form-group">
              <label>Name: </label><input class="form-control" name="name" data-type="text" type="text" required>
            </div>
            <div class="form-group">
              <label>Email: </label><input class="form-control" name="email" data-type="email" type="email" required>
            </div>
            <div class="form-group">
              <label>Request: </label><input class="form-control" name="request" data-type="text" type="text">
            </div>
            <div class="form-group">
              <label>Files: </label><input class="form-control" name="files" data-type="file" type="file" multiple>
              <div class="progress hidden">
                <div id="files_progress" class="progress-bar" role="progressbar" aria-valuenow="0"
                aria-valuemin="0" aria-valuemax="100" style="width:0">
                  <span class="sr-only">0%</span>
                </div>
              </div>        
            </div><div id="fg-errors" class="form-group">
            </div>
            <button class="btn btn-primary btn-lg btn-block" id="btn-submit" type="submit" data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i> Submitting...">Submit</button> 
            </form>
        </div>
    {{/block}}
    
    {{#block "scripts"}}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
    <script src="https://websitedemo-4db9.restdb.io/assets/js/jquery-serialize-object.min.js"></script>
    <script src="https://websitedemo-4db9.restdb.io/assets/js/jquery.datetimepicker.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.5.1/lodash.min.js"></script>
    <script>
    
    $(function () {
    
      // put your own error messages and/or message translation logic here
    
      var errorMessages = {
        "REQUIRED": "This field is required",
        "UNIQUE": "This value already exists",
        "TYPE": "Invalid data type",
        "REGEX":"Invalid data format",
        "number": "Must be an integer number",
        "money": "Must be a number with max two decimals",
        "JSON":"Not a valid JSON",
        "float_number":"Must be a decimal number",
        "email": "Must be a valid email",
        "FILESIZE": "Upload exceeds file size limit per field (max 5 MB)",
        "UPLOADERROR": "Unable to upload file, please try again",
        "GENERIC_ERROR": "A server error occured, please reload page"
      }
    
      var successMessage = "Thank you!";
    
      // enable javascript datetimepicker unless supported
      // Docs and settings: http://xdsoft.net/jqplugins/datetimepicker/
    
      $.datetimepicker.setLocale('en');
    
      // if missing support for datetime, then use jquery.datetimepicker
    
      if (!Modernizr.inputtypes.datetime){
          $("input[data-type=date]").datetimepicker({timepicker:false,format:"Y/m/d"}).attr("type","text");
          $("input[data-type=datetime]").datetimepicker({}).attr("type","text");
          $("input[data-type=time]").datetimepicker({datepicker:false,format:"H:i",value:"12:00"}).attr("type","text");
      }
    
      $("#webcontact-form input[data-type=file], #webcontact-form input[data-type=image]").on("change",function(){
        $(this).data("uploadedfiles",[]);    
      });
    
      var apikey = "57968a20f110a1d9187b9000"; // // TODO: INSERT YOUR CORS API KEY HERE
    
      if (!apikey) alert("Please insert a CORS API key");
    
      var ajaxSettings = {
        "async": true,
        "crossDomain": true,
        "url": "https://websitedemo-4db9.restdb.io/rest/webcontact",
        "method": "POST",
        "headers": {
          "x-apikey": apikey,
          "content-type": "application/json"
        },
        "processData": false
      }
    
      var ajaxSettingsAttachments = {
         "async": true,
         "url": "https://websitedemo-4db9.restdb.io/media",
         "method": "POST",
         "contentType": false,
         "headers": {
           "x-apikey": apikey
         },
         "cache": false,
         "processData": false
       }
    
      function uploadAttachment(item){
        var deferred = $.Deferred();
        var datatype = $(item).attr("data-type");
        var element_name = $(item).attr("name");
        var formData = new FormData();
        var files = $(item)[0].files;
        var totalsize = 0;
        var files_to_upload = []
        _.each(files,function(file){
          // ignore non-images
          if(datatype==="image" && !file.type.match('image.*')){
            return;
          }else{
            files_to_upload.push(file);
            totalsize += file.size;        
          }
        });
    
        // check max upload file size for basic plan
        if (totalsize<=5000000){
          _.each(files_to_upload,function(file){
            formData.append(element_name, file, file.name);
          });
          var asa = _.clone(ajaxSettingsAttachments);
          asa.xhr = function() {
            var xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener("progress", function(evt) {
              if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                percentComplete = parseInt(percentComplete * 100)+"%";
                $("#"+element_name+"_progress")
                .css("width",percentComplete)
              }
            }, false);
            return xhr;
          }
          asa.data = formData;
          var uploadedbefore = $(item).data("uploaded");
          if (!uploadedbefore){
            $("#"+element_name+"_progress").parent().removeClass("hidden");
            $("#btn-submit").button("loading");
            $.ajax(asa)
            .success(function(data){
              var result = data.ids || [];
              var successObj = {};
              successObj[element_name] = result;
              $(item).data("uploaded",result);
              deferred.resolve(successObj);       
            })
            .fail(function(){
              deferred.reject({field: element_name, error: errorMessages.UPLOADERROR});
            });
          }else{
            var obj = {};
            obj[element_name]=uploadedbefore;
            deferred.resolve(obj);
          }
        }else{
          deferred.reject({field: element_name, error: errorMessages.FILESIZE});
        }
        return deferred.promise();
      }
    
      function postForm() {
    
        // clear errors
        $("#webcontact-form .has-error").removeClass("has-error");
        $("#webcontact-form .help-block").remove();
    
        $("#btn-submit").button("loading");
    
        // get the form data
        var formObj = $("#webcontact-form").serializeObject();
    
        // get attachments from inputs
        var attachments = [];
    
        $("#webcontact-form input[data-type=file], #webcontact-form input[data-type=image]").each(function(input){
          var files = $(this)[0].files;
          if(files && files.length>0){
            attachments.push($(this));
          }
        });
    
        var attachFuncs = [];
        _.each(attachments,function(attachment){
          attachFuncs.push(uploadAttachment(attachment));
        });
      
        // upload all attachments and return with ids when done
        $.when.apply(null,attachFuncs)
          .done(function(){
            // get the attachment id's from arguments and store into form obj
    
            _.each(arguments,function(fieldObj){
              formObj = _.assign(formObj,fieldObj);
            });
    
           // submit the whole form with attachment ids 
    
           ajaxSettings.data = JSON.stringify(formObj);
            $.ajax(ajaxSettings)
            .done(function (response) {
              // replaces form with a thank you message, please replace with your own functionality
              $(".form-container").replaceWith("<div class='lead'>"+successMessage+"</div>");
            })
            .fail(function (response) {
              $("#btn-submit").button("reset");
              var error = response.responseJSON;
              if (error && error.name==="ValidationError"){
                _.each(error.list,function(fielderr){
                  var inputSelector = "[name="+fielderr.field+"]";
                  var errorMessageCode = fielderr.message[1];
                  var errorMessage = errorMessages[errorMessageCode] || "Invalid value";
                  if (errorMessageCode==="TYPE"){
                    var fieldType = $(inputSelector).data("type");
                    errorMessage = errorMessages[fieldType] || "Invalid value";
                  }
                  $(inputSelector).after("<div class='help-block'>"+errorMessage+"</div>");
                  $(inputSelector).parents(".form-group").addClass("has-error");
                });
              }
              else{
                var msg = (ajaxSettings.headers["x-apikey"] && ajaxSettings.headers["x-apikey"].length < 24) ? "Missing API-key": "Server Error";
                alert(msg);
              }
            });
          })
          .fail( function (response) {
            $("#btn-submit").button("reset");
            if (response.field && response.error){
              var inputSelector = "[name="+response.field+"]";
              $(inputSelector).after("<div class='help-block'>"+response.error+"</div>");
              $(inputSelector).parents(".form-group").addClass("has-error");
            }else{
              var errorMessage = errorMessages.GENERIC_ERROR || "Problem submitting form";
              $("#fg-errors").addClass("has-error")
              .append("<div class='help-block'>"+errorMessage+"</div>");
            }
          });
      };
    
      $("#webcontact-form").submit(function (event) {
            postForm();
            event.preventDefault();
            return false;
        });
    });
    </script>
      
    {{/block}}
    
     {{#block "sidebar"}}
    
    {{#include "contact-partial"}}
    {{/include}}
    
    {{/block}}
    
    
{{/inherit}}