I have a HTML form in JSP page, and in the I have a JavaScript validation. The user must enter one field: name or id or year, and a java file will search the student in database by name or by id or by year. The JavaScript alerts when no field is filled and performs the action if one field is filled.
<html>
<head>
<title>Student to search into database</title>
<script language="javascript">
function validate2(objForm){
int k = 0;
if(objForm.name.value.length==0){
objForm.name.focus();
k++;
}
if(objForm.year.value.length==0){
objForm.year.focus();
k++;
}
if(objForm.id.value.length==0){
objForm.year.focus();
k++;
}
if(k == 0){
return false;
}
return true;
}
</script>
</head>
<body bgcolor=#ADD8E6><center>
<form action="FoundStudents.jsp" method="post" name="entry2" onSubmit="validate2(this)">
<input type="hidden" value="list" name="seek_stud">
...........................................................................................
The problem is I want to process the parameter which I receive in FoundStudents.jsp: If I get the year, I look in DB which student(s) are in that year and display all that student(s)' data(do that in a java file). How could I do that in FoundStudents.Jsp without checking again which field is filled(I've done that in JavaScript from SearchStudent.jsp). I mean the FoundStudents.jsp calls a method in the java file for searching and displaying.
I tried by now with the input hidden that worked, but that is for more forms. I have only 1.
FoundStudent.jsp
<%#page import="stud.diploma.students.StudentsManager"%>
<%#page import="stud.diploma.students.Student"%>
<%#page import="java.util.ArrayList"%>
<%#page import="stud.diploma.database.ConnectionsManager"%>
<%# page language="java" import="java.sql.*, java.lang.*" %>
<%
Student search = null;
if(request.getParameter("seek_stud") != null){
//reading params from the SearchStudent form
String name = request.getParameter("name");
String year_prime = request.getParameter("year");
int year, id;
try{
year = Integer.parseInt(year_prime);
}catch(Exception e1){
year = 0;
}
String id_prime = request.getParameter("id");
try{
id = Integer.parseInt("id");
}catch(Exception e2){
id = 0;
}
if(name.length() != 0){
search = StudentsManager.getInstance().studByName(name);
}
if(year > 0){
search = StudentsManager.getInstance().studByYear(year);
}
if(id > 0){
search = StudentsManager.getInstance().studById(id);
}
if(search != null){
%>
<html>
<body bgcolor=#4AA02C>
<center>
<h2>Student's data</h2>
<table border="1" cellspacing="1" cellpadding="8" bgcolor= #EBDDE2>
<tr>
<td bgcolor= #FF9966><b>ID</b></td>
<td bgcolor= #FF9966><b>Name</b></td>
<td bgcolor= #FF9966><b>Year</b></td>
</tr>
<tr>
<td><%= search.getId()%></td>
<td><%= search.getName()%></td>
<td><%= search.getYear()%></td>
</tr>
</table>
</center>
</body>
</html>
<%}else{%>
<%
String redirectURL = "MainMenu.html";
response.sendRedirect(redirectURL);
%>
<%}%>
<%}%>
This FoundStudent.jsp is for the version of multiple forms (using hidden input) that worked. (the javascript test was just a little bit different, I typed it insted of what I had in the beginning)
It searched by name and by year only. Didn't search by ID (I had exception here <td><%= search.getId()%></td> I'm still trying to see how to deal with it. ID is a AUTO_INCREMENT PRIMARY KEY)
Lines like : search = StudentsManager.getInstance().studByName(name);
Search is a Student type object. (Object Student is creaded in a java file)
StudentsManager is a java class that receives calls to it's methods from JSP. getInstance() creates an instance of StudentsManager. Method studByName(name) receives the parameter name from the form and searches it in the database.
So I changed the (java)script to:
<script language="javascript">
function validateSea(){
if(document.entry2.name.value != ''){
return true;
}
else
if(document.entry2.year.value != ''){
return true;
}
alert('Please fill one field.');
return false;
}
</script>
</head>
which is for 1 form. I'm not sure if I did the correct thing, but in FoundStudents.jsp, where I receive the parameters of the form, I test:
if((request.getParameter("year") != null)||(request.getParameter("name") != null)){
//reading params from the SearchStudent form
................}
It works this way.
Related
Trying to learn Google Web Apps, I'm having the hardest time in 4 years of studying Google services. At this point, with help from other people, I have assembled a Web App form which successfully processes a few questions and accepts the submission of a file, sending the file to a folder on my Google Drive, appending the form answers to a Google Sheet, and sending me an email alerting me to the form submission. I think I understand how it works, but in trying to make the simplest of changes to it, it stopped working and gave me an error message I don't what to do with.
The form requires the user to upload an image of their COVID vaccination card. Since some people have more than one card, the form allows the user to upload more than file. This screen shot shows what the form displays upon successful submission.
The form fields and their answers remain in place, and below them appears the message "Uploaded successfully! You may upload another." What I want to have happen, besides a message like this appearing, is for all form fields and their answers disappear except for the Vacc Card/Choose File and Submit buttons.
So, I am trying to follow the instructions in this video from the highly popular YouTube Channel Learn Google Sheets & Excel Spreadsheets: Create Views (Pages) in Web App - Google Apps Script Web App Tutorial - Part 7
In this video, we see how to make the submission of a Web App form add to the current URL the string "?v=form" or "?v=whatever" and have the DoGet(e) function offer a different HTML file depending on whether the URL contains "&v" and if does, what follows that.
However, in following THE VERY FIRST STEP in the instructions, the App stopped working. All I did was cut what was inside the function doGet(e), place it inside a new function loadForm(), and put inside the doGet a calling of that function:
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
}
This one change caused the App to fail, returning nothing but a screen reading "The script completed but did not return anything."
My code:
/*
* Original doGet function; works fine. */
// function doGet(e){
// return HtmlService.createTemplateFromFile('index').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
// .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
// }
/** Step that caused this to fail: */
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
} // else {HtmlService.createHtmlOutput('<h1>Hello<h1>')} // This would have been the next step, and the step after that making a second HTML file.
// Commenting out this step did NOT help.
}
function loadForm(){
return HtmlService.createTemplateFromFile('index').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
} /** There you have it. All that follows is part of what works. */
function uploadFiles(formObject) {
var folderID = "1nvhxUoj9uRlE0KpBNjW3cosIuuRpAQly"; // Massage / VaccinationCards
try {
var folder = DriveApp.getFolderById(folderID);
var fileUrl = "";
//Upload file if exists
if (formObject.myFile.length > 0) {
var name = formObject.name;
var namePref = formObject.namePref;
var pronouns = formObject.pronouns;
var ready = formObject.ready;
var email = formObject.email;
var phone = formObject.phone;
var callTimes = formObject.callTimes;
var questions = formObject.questions;
var blob = formObject.myFile;
var file = folder.createFile(blob);
fileUrl = file.getUrl();
} else {
fileUrl = null;
}
SpreadsheetApp.openById("1S6RCLu8SKl0u8cVrEKd-3B71w5A-lvz0ikw_LPzgH50").getSheetByName("cards")
.appendRow([name, namePref, pronouns, ready, email, phone, callTimes, questions, fileUrl, new Date()]);
GmailApp.sendEmail('atiqzabinski#gmail.com', 'New Vax Card Uploaded!', 'Hey sweetie, smells like business! https://docs.google.com/spreadsheets/d/1S6RCLu8SKl0u8cVrEKd-3B71w5A-lvz0ikw_LPzgH50/edit', {name: 'Vacc Card Robot'});
return fileUrl;
} catch (error) {
return error.message;
}
}
My HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body style = "background:none transparent;">
<!-- <link href="/tpm-styles.css" rel="stylesheet" type="text/css"> -->
<link href="https://transformphillymassage.com/tpm-styles.css" rel="stylesheet" type="text/css">
<link href="https://transformphillymassage.com/formstyles.css" rel="stylesheet" type="text/css">
<form id="myForm" onsubmit="handleFormSubmit(this)">
<p>
<label for="FormControlFile">Legal Name:</label>
<input name="name" class="form-control-file" type="text" size="35" required/>
<br>
<label for="FormControlFile">Preferred Name:</label>
<input name="namePref" class="form-control-file" type="text" size="30">
<br> <label for="FormControlFile">Pronouns:</label>
<input name="pronouns" class="form-control-file" type="text" size = "35">
</p>
<p>
<label for="FormControlFile">Choose One:</label>
<!-- <select id = "id_ready" name = "ready" class="form-control-file" required/> -->
<!-- <select id = "id_ready" name = "ready" required/> -->
<select name = "ready" class="form-control-file" required/>
<option value = "I'm ready to book!">I'm ready to book!</option>
<option value = "I have questions.">I have questions.</option>
</select>
</p>
<p>
<label for="FormControlFile">email:</label>
<input name="email" class="form-control-file" type="text" size = "40" required/>
<br>
<label for="FormControlFile">Phone Number:</label>
<input name="phone" class="form-control-file" type="text" size = "28" />
<br>
<label for="FormControlFile">Best Times To Call:</label><br>
<input name="callTimes" class="form-control-file" type="text" size="50"/>
</p>
<p>
<label for="FormControlFile">Vacc Card:</label>
<input name="myFile" class="form-control-file" type="file" required/>
</p>
<p>
<label for="FormControlFile">Questions / Comments:</label><br>
<textarea name ="questions" class="form-control-file" cols="45" rows="4"></textarea>
<br>
<button type="submit"><span class="charm spanlavender">Submit</span></button>
</p>
</form>
<div id="urlOutput"></div>
<script>
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject){
google.script.run.withSuccessHandler(updateUrl).withFailureHandler(onFailure).uploadFiles(formObject);
}
function updateUrl(url) {
var div = document.getElementById('urlOutput');
if(isValidURL(url)){
div.innerHTML = '<div class="alert alert-success" role="alert">Uploaded successfully!<br>You may upload another.</div>';
// document.getElementById("myForm").reset();
} else {
//Show warning message if file is not uploaded or provided
div.innerHTML = '<div class="alert alert-danger" role="alert">'+ url +'!</div>';
}
}
function onFailure(error) {
var div = document.getElementById('urlOutput');
div.innerHTML = '<div class="alert alert-danger" role="alert">'+ error.message +'!</div>';
}
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
return (res !== null);
}
</script>
</body>
</html>
return is missing on the else part of your if-else statement
Replace your doGet function by
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
} else {
return HtmlService.createHtmlOutput('<h1>Hello<h1>')
}
}
Below are a couple of function that could be used to debug your doGet function by using the Google Apps Script editor.
/**
* Test case 1: v parameter equal to 'form'
*
*/
function test_1_doGet(){
const e = {
parameter: {}
};
e.parameter.v = 'form';
doGet(e);
}
/**
* Test case 2: No v parameter
*
*/
function test_1_doGet(){
const e = {
parameter: {}
};
doGet(e);
}
Related
Google App Script how to load different pages using HTML Service?
How can I test a trigger function in GAS?
getting parameters from a url returns 'parameter is undefined"
How to get a URL string parameter passed to Google Apps Script doGet(e)
Serve separate HTML pages Google apps script not working
doGet(e) parameter undefined
I've got JS form validation code and have to write HTML to it. Unfortunately, something is wrong. Could you please tell me what I am doing wrong? When I click submit button there is no change.
window.onload = init;
function validateForm() {
var user = document.forms["myForm"]["user"].value;
var password = document.forms["myForm"]["password"].value;
if (user == "") {
document.getElementById("poleUser").innerHTML = "<img src='./unchecked.gif'/> Proszę podać nazwisko";
} else {
document.getElementById("poleUser").innerHTML = "<img src='./checked.gif'/>";
}
if (password.lenght < 6) {
document.getElementById("poleHasla").innerHTML =
"<img src='./unchecked.gif'/> Hasło musi zawierać co najmnej 6 znaków";
} else {
document.getElementById("poleHasla").innerHTML = "<img src='./checked.gif'/>";
}
return false;
}
function init() {
document.getElementsByName('myForm').onsubmit = validateForm;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="myForm">
Name: <input type="texts" name="user"><span id="poleUser"></span><br>
Password: <input type="password" name="password"><span id="poleHasla"></span>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
You need to properly format the function calls
document.getElementsByName('myForm').onsubmit = validateForm;
should be
document.getElementsByName('myForm').onsubmit = validateForm();
(Notice the parentheses at the end).
However, I'd just like to address how you're doing this. In most cases, assigning the onSubmit property statically makes more sense than doing it dynamically. In this case, there really doesn't seem to be any reason for initializing the property using JS.
I have a webapp form and I'm looking for a way to push the value of the form into google spreadsheet.
My current attempt is to assign a name to each form input (a1,a2,a3...) then attempt to iterate the form values into an array like this:
Code.gs
function doGet(e) {
return HtmlService
.createTemplateFromFile('Index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE)
}
function writeForm(form) {
var ss =
SpreadsheetApp.openById('1bKrGjBV*****');
var sheet = ss.getSheets()[0];
var data = ss.getDataRange().getValues();
var input = [''];
var ndata = form
for(var j=0;j<data.length;j++){
var value = form.a+j
input.push(value)
}
for(var k=0;k<data.length;k++){
sheet.getRange(k+1,4).setValue(ndata[k]);
}
var range = sheet.getRange(1, 5);
}
function getData(){
return SpreadsheetApp
.openById('1bKrGjBV*****')
.getSheets()[0]
.getDataRange()
.getValues();
}
Index.html
<body>
<center><h1>Produce Inventory Form </h1></center>
<style>
table,th,td{border:1px solid black;}
</style>
<? var data = getData(); ?>
<form id="invform">
<input type = "submit" value="Submit" onclick
="google.script.run.writeForm(this.parentNode)">
<table align="center">
<tr><th>Code</th><th>Name</th><th>ChName</th><th>On Hand</th></tr>
<? for(var i=0;i<data.length;i++){ ?>
<tr>
<th><?= data[i][0] ?></th>
<th><?= data[i][1] ?></th>
<th><?= data[i][2] ?></th>
<th><input type = "text" style="width:40px" min="0" maxlength="3" name=a<?
=i ?>>
</tr>
<? } ?>
</table>
</body>
With this method, the problem I'm getting into is
var value = form.a+j
Doesn't do what I was hoping for, which is to assign a variable to form.a1, form.a2, form.a3, ... then push it into an array.
I'm pretty sure there's a better way but I have yet to find a solution. Apologize for the messy code, but I was focused on getting the result.
How about a following modification?
Modification points :
For Index.html, </form> is missing.
About form.a+j, you can retrieve the values using form["a" + j].
ndata is JSON like {a1: "value", a2: "value"}. So when ndata is imported to cells, it becomes undefined.
When several values are imported to cells, the importing efficiency becomes higher by using setValues().
When these are reflected to your script, the modified script is as follows. The values inputted to forms are imported to "D1:D" of spreadsheet.
Modified script :
Code.gs
function doGet(e) {
return HtmlService
.createTemplateFromFile('Index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE)
}
function writeForm(form) {
var ss = SpreadsheetApp.openById('1bKrGjBV*****');
var sheet = ss.getSheets()[0];
var data = ss.getDataRange().getValues();
var input = []; // Modified
// var ndata = form
for(var j=0;j<data.length;j++){
var value = form["a" + j]; // Modified
input.push([value]) // Modified
}
sheet.getRange(1, 4, input.length, input[0].length).setValues(input); // Added
// for(var k=0;k<data.length;k++) {
// sheet.getRange(k+1,4).setValue(ndata[k]);
// }
// var range = sheet.getRange(1, 5);
}
function getData(){
return SpreadsheetApp
.openById('1bKrGjBV*****')
.getSheets()[0]
.getDataRange()
.getValues();
}
Index.html
<body>
<center><h1>Produce Inventory Form </h1></center>
<style>
table,th,td{border:1px solid black;}
</style>
<? var data = getData(); ?>
<form id="invform">
<input type = "submit" value="Submit" onclick="google.script.run.writeForm(this.parentNode)">
<table align="center">
<tr><th>Code</th><th>Name</th><th>ChName</th><th>On Hand</th></tr>
<? for(var i=0;i<data.length;i++){ ?>
<tr>
<th><?= data[i][0] ?></th>
<th><?= data[i][1] ?></th>
<th><?= data[i][2] ?></th>
<th><input type = "text" style="width:40px" min="0" maxlength="3" name=a<?= i ?>>
</tr>
<? } ?>
</table>
</form> <!-- Added -->
</body>
If I misunderstand your question, I'm sorry.
Ok, this is related to the question I asked a short while ago: Silverstripe/PHP/jQuery - Once form has been filled out by user, prevent it from automatically appearing for each visit
Something has changed since then. Per request of the client, the form must not automatically appear if the user has already filled it out and has thus been placed into SharpSpring. Originally, I was creating a cookie on successful form submission using JavaScript. However, the latest concern is that it's not effective enough as cookies are registered only to certain devices and browsers, and users can clear their cookies at any time.
Essentially, the desired result is to prevent the form from automatically appearing if the user has been registered in SharpSpring (a separate domain) without having to rely on cookies.
Has anyone ever attempted something like this, checking to see if a user has submitted a form to another domain?
For reference, here is the form code I have setup:
<?php
/*
Plugin Name: SharpSpring Form Plugin
Description: A custom form plugin that is SharpSpring-compatible and uses HTML, CSS, jQuery, and AJAX
Version: 1.0
*/
define('SSCFURL', WP_PLUGIN_URL . "/" . dirname(plugin_basename(__FILE__)));
define('SSCFPATH', WP_PLUGIN_DIR . "/" . dirname(plugin_basename(__FILE__)));
function sharpspringform_enqueuescripts()
{
wp_enqueue_script('jquery-src', SSCFURL . '/js/jquery.js', array('jquery'));
wp_enqueue_script('jquery-ui', SSCFURL . '/js/jquery-ui.js', array('jquery'));
wp_enqueue_script('boootstrap', SSCFURL . '/js/bootstrap.js', array('jquery'));
wp_localize_script('sharpspringform', 'sharpspringformajax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'sharpspringform_enqueuescripts');
function sharpspringform_show_form()
{
wp_enqueue_style( 'boilerplate', SSCFURL.'/css/boilerplate.css');
wp_enqueue_style( 'bootstrapcss', SSCFURL.'/css/bootstrap.css');
wp_enqueue_style( 'bookregistration', SSCFURL.'/css/Book-Registration.css');
wp_enqueue_style( 'formstyles', SSCFURL.'/css/styles.css');
?>
<div class="mobile-view" style="right: 51px;">
<a class="mobile-btn">
<span class="glyphicon glyphicon-arrow-left icon-arrow-mobile mobile-form-btn"></span>
</a>
</div>
<div class="slider register-photo">
<div class="form-inner">
<div class="form-container">
<form method="post" enctype="multipart/form-data" class="signupForm" id="browserHangFormPV">
<a class="sidebar">
<span class="glyphicon glyphicon-arrow-left icon-arrow arrow"></span>
</a>
<a class="closeBtn">
<span class="glyphicon glyphicon-remove"></span>
</a>
<h2 class="text-center black">Sign up for our newsletter.</h2>
<p class="errors-container light">Please fill in the required fields.</p>
<div class="success">Thank you for signing up!</div>
<div class="form-field-content">
<div class="form-group">
<input class="form-control FirstNameTxt" type="text" name="first_name" placeholder="*First Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control LastNameTxt" type="text" name="last_name" placeholder="*Last Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control EmailTxt" type="email" name="email" placeholder="*Email"
autofocus="">
</div>
<div class="form-group">
<input class="form-control CompanyTxt" type="text" name="company" placeholder="*Company"
autofocus="">
</div>
<div class="form-group submit-button">
<button class="btn btn-primary btn-block button-submit" type="button">SIGN ME UP</button>
<img src="/wp-content/plugins/sharpspring-form/img/ajax-loader.gif" class="progress" alt="Submitting...">
</div>
</div>
<br/>
<div class="privacy-link">
<a href="[privacy policy link]" class="already" target="_blank"><span
class="glyphicon glyphicon-lock icon-lock"></span>We will never share your information.</a>
</div>
</form>
<input type="hidden" id="gatewayEmbedID" value="<?php echo get_option( 'pv_signup_sharpspring_ID' ); ?>" />
<script type="text/javascript">
var embedID = document.getElementById("gatewayEmbedID").value;
var __ss_noform = __ss_noform || [];
__ss_noform.push(['baseURI', 'https://app-3QNAHNE212.marketingautomation.services/webforms/receivePostback/[redacted]']);
__ss_noform.push(['form', 'browserHangFormPV', embedID]);
__ss_noform.push(['submitType', 'manual']);
</script>
<script type="text/javascript" src="https://koi-3QNAHNE212.marketingautomation.services/client/noform.js?ver=1.24" ></script>
</div>
</div>
</div>
<?php
}
function sharpspringform_shortcode_func( $atts )
{
ob_start();
sharpspringform_show_form();
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode( 'sharpspringform', 'sharpspringform_shortcode_func' );
The form submission code with generates a cookie using JS:
;
(function ($) {
$(document).ready(function () {
var successMessage = $('.success');
var error = $('.errors-container');
var sharpSpringID = $('#gatewayEmbedID').val();
var submitbtn = $('.button-submit');
var SubmitProgress = $('img.progress');
var formdata = {};
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
submitbtn.click(function (e) {
resetErrors();
postForm();
});
function resetErrors() {
$('.signupForm input').removeClass('error-field');
}
function postForm() {
$.each($('.signupForm input'), function (i, v) {
if (v.type !== 'submit') {
formdata[v.name] = v.value;
}
});
submitbtn.hide();
error.hide();
SubmitProgress.show();
$.ajax({
type: "POST",
data: formdata,
url: '/wp-content/plugins/sharpspring-form/sharpsring-form-submission.php',
dataType: "json"
}).done(function (response) {
submitbtn.show();
SubmitProgress.hide();
if (response.errors) {
error.show();
var errors = response.errors;
errors.forEach(function (error) {
$('input[name="' + error + '"]').addClass('error-field');
})
}
else {
__ss_noform.push(['submit', null, sharpSpringID]);
setCookie('SignupSuccess', 'NewsletterSignup', 3650);
$('#browserHangFormPV')[0].reset();
$('.form-field-content').hide();
successMessage.show();
$('.button-submit').html("Submitted");
}
});
}
});
}(jQuery));
The jQuery code that sets up the form sliding animation and popup feature, as well as checks for the existence of the JS cookie created on successful form submit:
jQuery.noConflict();
(function ($) {
$(document).ready(function () {
//This function checks if we are in mobile view or not to determine the
//UI behavior of the form.
checkCookie();
window.onload = checkWindowSize();
var arrowicon = $(".arrow");
var overlay = $("#overlay");
var slidingDiv = $(".slider");
var closeBtn = $(".closeBtn");
var mobileBtn = $(".mobile-btn");
//When the page loads, check the screen size.
//If the screen size is less than 768px, you want to get the function
//that opens the form as a popup in the center of the screen
//Otherwise, you want it to be a slide-out animation from the right side
function checkWindowSize() {
if ($(window).width() <= 768) {
//get function to open form at center of screen
if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
setTimeout(formModal, 5000);
function formModal() {
slidingDiv.addClass("showForm")
overlay.addClass("showOverlay");
overlay.removeClass('hideOverlay');
mobileBtn.addClass("hideBtn");
}
}
}
else {
//when we aren't in mobile view, let's just have the form slide out from the right
if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
setTimeout(slideOut, 5000);
function slideOut() {
slidingDiv.animate({'right': '-20px'}).addClass('open');
arrowicon.addClass("glyphicon-arrow-right");
arrowicon.removeClass("glyphicon-arrow-left");
overlay.addClass("showOverlay");
overlay.removeClass("hideOverlay");
}
}
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("SignupSuccess");
if (user != "") {
return true;
} else {
return false;
}
}
/*
------------------------------------------------------------
Functions to open/close form like a modal in center of screen in mobile view
------------------------------------------------------------
*/
mobileBtn.click(function () {
slidingDiv.addClass("showForm");
slidingDiv.removeClass("hideForm");
overlay.addClass("showOverlay");
overlay.removeClass('hideOverlay');
mobileBtn.addClass("hideBtn");
});
closeBtn.click(function () {
slidingDiv.addClass("hideForm");
slidingDiv.removeClass("showForm");
overlay.removeClass("showOverlay");
overlay.addClass("hideOverlay")
mobileBtn.removeClass("hideBtn");
sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
});
/*
------------------------------------------------------------
Function to slide the sidebar form out/in
------------------------------------------------------------
*/
arrowicon.click(function () {
if (slidingDiv.hasClass('open')) {
slidingDiv.animate({'right': '-390px'}, 200).removeClass('open');
arrowicon.addClass("glyphicon-arrow-left");
arrowicon.removeClass("glyphicon-arrow-right");
overlay.removeClass("showOverlay");
overlay.addClass("hideOverlay");
sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
} else {
slidingDiv.animate({'right': '-20px'}, 200).addClass('open');
arrowicon.addClass("glyphicon-arrow-right");
arrowicon.removeClass("glyphicon-arrow-left");
overlay.addClass("showOverlay");
overlay.removeClass("hideOverlay");
}
});
});
}(jQuery));
I'm confused by the WordPress code here, rather than SilverStripe, it's not clear in your question which platform you're using.
Basically, if you want something more robust than cookies, you'll need to store the registration in the database and check it there (assuming the registration form is on your site). This means you handle the form submission on your site, send the data to the remote site and check the responses, and if all goes well, save the fact that the user has registered remotely into your database where you can check when deciding whether to show the form or not, next time.
If you don't have access to the registration form, or you want to also notice registrations made independently of your site, then you need to have an API you can query on the remote site in order to see if the user is registered.
I found a sharpspring API, but I'm not sure if it's relevant.
I am currently working on a grails project and am trying to create a one to many form. I have been using the tutorial at the link below to get started:
http://omarello.com/2010/08/grails-one-to-many-dynamic-forms/
The solution has a form with two field of data that are static and one dynamic fiwld where the user is allowed to add as many variables as they want and then save them. below you can see all the various files for this functionality:
Products.Groovy Domain Class
import org.apache.commons.collections.list.LazyList;
import org.apache.commons.collections.FactoryUtils;
/**
* Products
* A domain class describes the data object and it's mapping to the database
*/
class Products {
String productType
String product
List vars = new ArrayList()
//This represents a product belonging to a single department
static belongsTo = [dept:Depts]
static hasMany = [ vars:Dynam ]
static mapping = {
vars cascade:"all-delete-orphan"
}
def getVarsList() {
return LazyList.decorate(
vars,
FactoryUtils.instantiateFactory(Dynam.class))
}
static constraints = {
productType blank: false
product blank:false, size: 1..160
}
}
Dynam.groovy
class Dynam {
public enum VarType{
T("Testimonial"),
D("Dimentions"),
N("Networking")
final String value;
VarType(String value) {
this.value = value;
}
String toString(){
value;
}
String getKey(){
name()
}
static list() {
[T, D, N]
}
}
static constraints = {
index(blank:false, min:0)
data(blank:false)
type(blank:false, inList:VarType.list(), minSize:1, maxSize:1)
}
int index
String data
VarType type
boolean deleted
static transients = [ 'deleted' ]
static belongsTo = [ product:Products ]
def String toString() {
return "($index) ${data} - ${type.value}"
}
}
ProductsController.Groovy
Creation Function
def createDynProduct(){
def productsInstance = new Products()
productsInstance.properties = params
//This is used in order to create a new User Object for the current User logged in
def userObjects = springSecurityService.currentUser
//This passes the 2 models to the view one being Products and the other a User Department
[productsInstance: productsInstance, dept: userObjects.dept]
}
Save Function
def save() {
def productInfo = "dynam"
def userObjects = springSecurityService.currentUser
def dept = Depts.findByName(params.dept.name)
def product = new Products(product:productInfo, productType:params.productType, dept: dept, vars:params.varsList)
def _toBeRemoved = product.vars.findAll {!it}
// if there are vars to be removed
if (_toBeRemoved) {
product.vars.removeAll(_toBeRemoved)
}
//update my indexes
product.vars.eachWithIndex(){phn, i ->
if(phn)
phn.index = i
}
//If the the save is not successful do this
if (!product.save(flush: true)) {
render(view: "create", model: [productsInstance: product, dept: userObjects.dept])
return
}
redirect(action: "show", id: product.id)
}
createDynProduct.gsp
<%# page import="com.tool.Products" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name='layout' content='springSecurityUI'/>
<g:set var="entityName" value="${message(code: 'messages.label', default: 'Products')}" />
<title><g:message code="default.create.label" args="[entityName]" /></title>
</head>
<body>
<g:renderErrors bean="${productsInstance}" />
<g:form action='save' name='ProductForm' >
<br/>
<!-- Render the product template (_dynam.gsp) here -->
<g:render template="dynam" model="['productsInstance':productsInstance]"/>
<!-- Render the product template (_dynam.gsp) here -->
<div class="buttons">
<g:submitButton name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" />
</div>
</g:form>
<!-- Render the var template (_var.gsp) hidden so we can clone it -->
<g:render template='var' model="['var':null,'i':'_clone','hidden':true]"/>
<!-- Render the var template (_var.gsp) hidden so we can clone it -->
</body>
</html>
_dynam.gsp
<div class="dialog">
<table>
<tbody>
<tr class="prop">
<td valign="top" class="name">
<label for="productType">Product Type</label>
</td>
<td>
<g:textField name='productType' bean="${productsInstance}" value="${productsInstance.productType}"
size='40'/>
</td>
</tr>
<tr class="prop">
<td valign="top" class="name">
<label for="Vars">Vars</label>
</td>
<!-- Render the vars template (_vars.gsp) here -->
<g:render template="vars" model="['productsInstance':productsInstance]" />
<!-- Render the vars template (_vars.gsp) here -->
</tr>
<tr class="prop">
<td valign="top" class="name">
<label for="Department">Department</label>
</td>
<td>
<g:textField name='dept.name' readonly="yes" value="${dept.name}" size='40'/>
</td>
</tr>
</tbody>
</table>
</div>
_vars.gsp
<script type="text/javascript">
var childCount = ${productsInstance?.vars.size()} + 0;
function addVar(){
var clone = $("#var_clone").clone()
var htmlId = 'varsList['+childCount+'].';
var varInput = clone.find("input[id$=number]");
clone.find("input[id$=id]")
.attr('id',htmlId + 'id')
.attr('name',htmlId + 'id');
clone.find("input[id$=deleted]")
.attr('id',htmlId + 'deleted')
.attr('name',htmlId + 'deleted');
clone.find("input[id$=new]")
.attr('id',htmlId + 'new')
.attr('name',htmlId + 'new')
.attr('value', 'true');
varInput.attr('id',htmlId + 'data')
.attr('name',htmlId + 'data');
clone.find("select[id$=type]")
.attr('id',htmlId + 'type')
.attr('name',htmlId + 'type');
clone.attr('id', 'var'+childCount);
$("#childList").append(clone);
clone.show();
varInput.focus();
childCount++;
}
//bind click event on delete buttons using jquery live
$('.del-var').live('click', function() {
//find the parent div
var prnt = $(this).parents(".var-div");
//find the deleted hidden input
var delInput = prnt.find("input[id$=deleted]");
//check if this is still not persisted
var newValue = prnt.find("input[id$=new]").attr('value');
//if it is new then i can safely remove from dom
if(newValue == 'true'){
prnt.remove();
}else{
//set the deletedFlag to true
delInput.attr('value','true');
//hide the div
prnt.hide();
}
});
</script>
<div id="childList">
<g:each var="var" in="${productsInstance.vars}" status="i">
<!-- Render the var template (_var.gsp) here -->
<g:render template='var' model="['var':var,'i':i,'hidden':false]"/>
<!-- Render the var template (_var.gsp) here -->
</g:each>
</div>
<input type="button" value="Add Var" onclick="addVar();" />
_var.gsp
<div id="var${i}" class="var-div" <g:if test="${hidden}">style="display:none;"</g:if>>
<g:hiddenField name='varsList[${i}].id' value='${var?.id}'/>
<g:hiddenField name='varsList[${i}].deleted' value='false'/>
<g:hiddenField name='varsList[${i}].new' value="${var?.id == null?'true':'false'}"/>
<g:textField name='varsList[${i}].number' value='${var?.data}' />
<g:select name="varsList[${i}].type"
from="${com.tool.Dynam.VarType.values()}"
optionKey="key"
optionValue="value"
value = "${var?.type?.key}"/>
<span class="del-var">
<img src="${resource(dir:'images/skin', file:'icon_delete.png')}"
style="vertical-align:middle;"/>
</span>
</div>
The solution works in part so you can go to the products page and it loads with the fields and the dynamic fields are added to the view fine and I can enter the data. However when I click save the data for the static fields is persisted but the dynamic vars are not saved to the domain.
I don’t get any errors but I believe it has something to do with the save function line below and the vars:params.varsList in particular.
def product = new Products(product:productInfo, productType:params.productType, dept: dept, vars:params.varsList)
I have checked the varsList data using println and it returns null, can someone please help with this?
Thanks in advance