Lift - Returning Errors and Updating Parent Div Class From Ajax Form - scala

I have an ajax form which which is currently returning errors using the S.error() method. This is fine but I also want to add a new css class to one of the elements parent div tags. I have tried to do this with the JE.Call() method with no avail. Is anyone could point me in the right direction it would be really appreciated.
Snippet Code
class Register {
private var user = User.createRecord
private var pw2 = ""
private var dob = ""
private var errors = new Array[String](7)
val whence = S.referer openOr "/"
Thread.sleep(400)
def registerUser(): JsCmd = {
errors(0) = User.validateUsername(user.username.is)
errors(1) = User.validateEmail(user.email.is)
errors(2) = User.validatePhone(user.phone.is)
errors(3) = User.validateCity(user.city.is)
errors(4) = User.validateDOB(dob)
errors(5) = User.validatePassword(user.uPw.is)
errors(6) = User.validateSecondPW(user.uPw.is, pw2)
if(errors.count(_ != "") == 0) {
user.uPw.set(User.hashPassword(user.uPw.is, user.id.is.toString))
user.dob.set(User.stringToDate(dob))
user.save
println("User id " + user.id.is.toString + " added to database")
S.redirectTo(whence)
}else{
if(errors(0) != "")
S.error("username-error", errors(0))
JE.Call("addError(username-error)")
......
}
}
def form = {
"id=username" #> SHtml.text("", user.username.set(_), "placeholder" -> "Username") &
"id=email" #> SHtml.email("", user.email.set(_), "placeholder" -> "Email") &
"id=phone" #> SHtml.text("", user.phone.set(_), "placeholder" -> "Tel") &
"id=city" #> SHtml.text("", user.city.set(_), "placeholder" -> "City") &
"id=dob" #> SHtml.text("", dob = _, "placeholder" -> "DOB") &
"id=password" #> SHtml.password("", user.uPw.set(_), "placeholder" -> "Password") &
"id=passwordCheck" #> SHtml.password("", pw2 = _, "placeholder" -> "Confirm Password") &
"type=submit" #> SHtml.ajaxSubmit("Register", () => registerUser, "class" -> "btn")
}
}
HTML Template
<h2>Register</h1>
<form class="lift:form.ajax?class=form-horizontal">
<div class="lift:Register.form">
<div id="id1" class="control-group">
<label class="control-label" for="username">Username:</label>
<div class="controls">
<input id="username">
<span id="username-error" class="help-inline"></span>
</div>
</div>
<div class="controls">
<button type="submit" ></button>
</div>
</div>
</form>
Javascript Function
<script>
function addError(id) {
$("#"+id).closest(".control-group").addClass("error");
}
addError("email-error")
</script>

Try to change the Call function.
JE.Call("addError","username-error").cmd

I recommend giving up on JavaScript abstractions in Lift and use plain Run Object everywhere. So In your case I'd use:
Run("addError(username-error)")

Related

Contact Form 7 Redirecting Page based on Button Clicked

HTML
<input name="Pay_Now" id = "submit" type="submit" value="PayNow" />
<input name="Pay_at_Venue" id = "submit" type="submit" value="PayatVenue" />
Script
The Script i am placing in theme editor under Footer.php
document.addEventListener( 'wpcf7mailsent', function( event ) {
var lpLocation = document.getElementById("submit").name;
if (lpLocation == "Pay_Now") {
location = 'https://rzp.io/l/fgpayment/';
} else if (lpLocation == "Pay_at_Venue") {
location = 'https://www.fingurukul.org/thank-you/';
} else {
// do nothing
}
}, false );
</script>
I am unable to find the mistake. What am i doing wrong>
Both the button are redirecting to same page
Please Help with your expertise
Thanks in advance

Data of radio button not being saved in Postgres DB even after a success message

Hi so I have these radio buttons where I want to save their data as json in my Postgres db . It is not being sent I get a message.success back that says I did but when i check my db nothing happens.
I don't exactly know where I am wrong so if u can help please do share.
PS: Im using Ant Design vue that's where the a- come from .
I do click on a button and it opens a modal where I have the radio buttons :
<template #modalite="{ record }">
<span>
<a-button
#click="showModalite(record)"
class="btn btn-sm btn-light mr-2"
>
<i class="fe fe-edit mr-2" />
Modalité
</a-button>
</span>
</template>
and here is my buttons code :
<a-modal
v-model:visible="visible"
:width="500"
#ok="ChangeModalite(modelInfo)"
>
<div class="row">
<a-radio-group name="radioGroup" v-model:value="traitement">
<div class="col-md-6">Négociation directe</div>
<div class="col-md-3">
<a-radio value="Négociation directe" v-model:checked="modalite.negociation" />
</div>
<div class="col-md-6">Appel à concurrence</div>
<div class="col-md-3">
<a-radio value="Appel à concurrence" v-model:checked="modalite.concurrence"/>
</div>
</a-radio-group>
</div>
</a-modal>
The script :
setup() {
const visible = ref(false)
const traitement = ref('Négociation directe');
const modalite = ref({
negociation:false,
concurrence:false,
})
const showModalite = (record) => {
modelInfo.value = record
modalite.value = { ...modalite.value, ...record.modalite }
visible.value = true
}
const ChangeModalite = (record) => {
console.log(record.id+": "+traitement.value)
axios.patch('/prop/' + record.id,{
modalite:modalite.value,
})
.then(()=>{
record.modalite=modalite.value
Object.assign(
dataSource.value.filter((item) => record.id === item.id),
record,
)
message.success(`successfully updated !!`)
visible.value = false
})
.catch((e)=>{
message.warning("smthg wrong ")
})
}
return {
dataSource,
modelInfo,
showModalite,
ChangeModalite,
modalite,
traitement,
}
},
}
So what happens now is i get the 'succefully updated ' msg without being really updated.where did i miss something?
I changed the type from json to string in my db everything works fine when I changed this line :axios.patch('/prop/' + record.id,{ modalite:modalite.value, }) to this axios.patch('/prop/' + record.id,{ modalite:traitement.value, })
so yeah data gets updated, still don't know why with the json type it's not working but at least i found a way if u have an explanation or suggestion it will be appriciated .

REACT Multiple Registration

I have a problem with React, so I created script and it doesn't work.
This should:
Render first state step (it's working) (Component First)
Here is error, it don't see default values.(name & email
After click Save And Continue it should save files to data.
And going to next steps in cases.
The error is
bundle.js:34147 Uncaught ReferenceError: email is not defined
function send(e){
e.preventDefault()
}
function nextStep(){
this.setState({
step:this.state.step + 1
})
}
function nextStep(){
this.setState({
step:this.state.step - 1
})
}
function saveAndContinue(e) {
e.preventDefault()
// Get values via this.refs
var data = {
name : this.refs.name.getDOMNode().value,
email : this.refs.email.getDOMNode().value,
}
this.props.saveValues(data)
this.props.nextStep()
};
var fieldValues = [
name : null,
email : null,
];
function saveValues(fields) {
return (
fieldValues = Object.assign({}, fieldValues, fields)
);
}
class Registration extends React.Component{
constructor () {
super()
this.state = {
step:1
}
}
render() {
switch (this.state.step) {
case 1:
return <First fieldValues={fieldValues}
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues} />
case 2:
return <Two fieldValues={fieldValues}
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues}/>
case 3:
return <Third fieldValues={fieldValues}
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues}/>
case 4:
return <Success fieldValues={fieldValues} />
}
}
}
class First extends React.Component{
render(){
return(
<form onSubmit ={send}>
<div className="group">
<input className="text" type="text" ref="name" defaultValue={this.props.fieldValues.name}/>
<span className="highlight"></span>
<span className="bar"></span>
<label>Write Name</label>
</div>
<div className="group">
<input className="text" type="email" ref="email" defaultValue={this.props.fieldValues.email} />
<span className="highlight"></span>
<span className="bar"></span>
<label>Write Your Mail</label>
</div>
<button onClick={this.saveAndContinue}>Save and Continue</button>
</form>
)
}
}
There is no Two, Third and Success classes in your code, so I'm assuming they are similar to the First class.
A global function doesn't need this keyword. But in this case, you have to put saveAndContinue inside First class if it need to access the state.
In React, normally you don't have to set default value for input.
Link the input value to the state, and then setState in onChange event.
The string in placeholder is shown when the state is empty.
The code below shows how to work with input tag in React:
<input
value={this.state.inputValue}
onChange={e => {
this.setState({ inputValue: e.target.value });
}}
type="text"
placeholder="default value"
/>
Note that the state will updates onChange rather than click the save button.
Does this solve your problem?

Receive Files in Drive and send Confirmation Email

I would like to create a form that allows anyone to upload multiple files to my drop box. But I would also like for the person that uploads the file to receive a confirmation email. The following code uploads the files but does send the email. Please help!
Here is the .gs
function doGet(e) {return HtmlService.createHtmlOutputFromFile('form.html');}
function sendEmails(form) {
var message= ", your abstract was submitted. Send other work by APR 20";
var subject = "Application Received";
MailApp.sendEmail(form.myEmail, subject, message);
}
function uploadFiles(form) {
try {
var dropbox = "New Abstracts";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile1;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
var blob = form.myFile2;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
return "File uploaded successfully " + file.getUrl();
} catch (error) {
return error.toString();
}
}
And here is the .html portion
<form id="myForm">
<input type="text" name="myName" placeholder="Your name..">
<input type="email" name="myEmail" placeholder ="Your email..">
<input type="file" name="myFile1" >
<input type="file" name="myFile2" >
<input type="submit" value="Upload File"
onclick="this.value='Uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode).sendEmails(this.parentNode);
return false;">
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
I trying this based on the codes found at:
http://www.labnol.org/internet/receive-files-in-google-drive/19697/
You can't append multiple calls to the script like this:
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode).sendEmails(this.parentNode);
Only uploadFiles (the first one being called) gets executed. Everything after that is getting ignored.
You can add the code inside sendEmails() to the uploadFiles() as one solution? Or add it to the success handler? Or have uploadFiles() call sendEmails() once it is done...

How to initialize and load values for MultiSelect / Numeric / FileUpload within a KendoUI Custom Popup Editor?

I'm trying out KendoUI Web and I'm trying to get the multiselect, numeric, and fileupload widgets to display and function correctly in my custom popup editor. When clicking the Edit button the popup does not display multiselect, numeric, and fileupload correct and I cannot load the default value from the grid row into the multiselect widget (for example '1,2' in the sample data. When i click the Save button within the popup editor all the fields should populate into my text box (which seem to be working ok). I would like to stick to the HTML method of initializing widgets rather than using MVC.
If someone could please help with my issues.
I am unsure how to initialize the widgets (multiselect, numeric, and fileupload) because if i put the javascript initialization in the template, I get errors.
I cannot load default values from the grid row into my multiselect dropdown.
Does anyone know what needs to be done to get this to work correctly?
Here is my current code at http://jsfiddle.net/Xwtq3/
<h2>")
Users</h2>")
")
<div id=""example"" class=""k-content"">")
")
<input name=""txtAdvancedSearchString"" type=""text"" onchange=""javascript:setTimeout('__doPostBack")
")
(\'txtAdvancedSearchString\',\'\')', 0)"" onkeypress=""if (WebForm_TextBoxKeyHandler(event) == false) return false;"" ")
")
id=""txtAdvancedSearchString"" />")
<script>")
var mydata = [{")
guid: ""D007DD39-540B-4bc3-9900-39A8B931EB19"",")
fullname: ""Jeff"",")
email: ""jeffkent#testemail.com"",")
groups: ""1,2"",")
administrator: ""1"",")
url: ""jeff.jpg""")
}, {")
guid: ""E8CFD49A-3B85-4093-AE52-F55C73E12A7B"",")
fullname: ""Frank"",")
email: ""testemail#email.com"",")
groups: ""3,4"",")
administrator: ""1"",")
url: ""todd.jpg""")
}];")
</script>")
<div id=""grid""></div>")
<div id=""details""></div>")
<script>")
var wnd,")
detailsTemplate;")
")
$(document).ready(function() {")
")
")
var grid = $(""#grid"").kendoGrid({")
dataSource: {")
pageSize: 20,")
data: mydata")
},")
pageable: true,")
groupable: true,")
selectable: ""row"",")
reorderable: true,")
sortable: true,")
filterable: true,")
columnMenu: true,")
height: 430,")
columns: [{")
field: ""fullname"",")
title: ""Full Name""")
}, {")
field: ""email"",")
title: ""Email""")
}, {")
field: ""groups"",")
title: ""Groups""")
}, {")
field: ""administrator"",")
title: ""User Role""")
}, {")
field: ""url"",")
title: ""File URL""")
}, {")
command: {")
text: ""Edit"",")
click: showDetails")
},")
title: "" "",")
width: ""140px""")
}]")
}).data(""kendoGrid"");")
")
wnd = $(""#details"")")
.kendoWindow({")
title: ""Download"",")
modal: true,")
visible: false,")
resizable: false,")
width: 300")
}).data(""kendoWindow"");")
")
detailsTemplate = kendo.template($(""#template"").html());")
});")
")
function showDetails(e) {")
e.preventDefault();")
")
")
var dataItem = this.dataItem($(e.currentTarget).closest(""tr""));")
wnd.content(detailsTemplate(dataItem));")
wnd.center().open();")
}")
</script>")
<script type=""text/x-kendo-template"" id=""template"">")
<div id = ""details-container"" > <h2 > View / Edit User </h2>")
<table cellspacing=""6"" cellpadding=""3"">")
<tr>")
<td><label ID=""lblID"" for=""txtID"">ID:</label > <br /> <input type = ""text""")
id = ""txtID""")
class = ""k-textbox""")
placeholder = """"")
value = ""#= guid #"" > </input></td > </tr>")
<td><label ID=""lblFirstName"" for=""txtFirstName"">First Name:</label > <br /> <input type = ""text""")
id = ""txtFirstName""")
class = ""k-textbox""")
placeholder = """"")
value = ""#= fullname #"" > </input></td > </tr>")
<tr>")
<td>")
<!--MultiSelect Dropdown-->")
")
<select name=""groups"" id=""groups"" class=""k-item"" multiple=""multiple"" data-role=""dropdownlist"">")
<option value=""1"">HR</option > < option value = ""2"" > 1099 < /option>")
<option value=""3"">Insurance Form</option > < option value = ""4"" > Claim Form < /option>")
<option value=""4"">Timeoff Requests</option >")
")
</select>")
")
<!--MultiSelect Dropdown end--></td >")
")
</tr>")
<tr><td> ")
<input id=""txtMaxAdmins"" type=""number"" value=""#=administrator#"" min=""0"" max=""100"" />")
")
")
")
</td></tr >")
")
")
<tr> <td> <label")
for = ""upload"" > Document Types: </label>")
Choose a transparent .png for best results<br /> <input id = ""upload""")
type = ""file"" value=""#=url#"" />")
")
")
</td></tr> <tr > <td colspan = ""2"" > <button ID = ""btnSave""")
class = ""k-button""")
onclick = ""CallServer()"" > Save </button></td> </tr>")
</table> </div>")
</script>")
<script>")
function CallServer() {")
var userinput = ($(""#txtID"").val()) + '|' + ($(""#txtFirstName"").val()) + '|' + ($(""#groups"").val());")
document.getElementById(""txtAdvancedSearchString"").value = userinput;")
")
//alert(userinput);")
__doPostBack('__Page', 'e');")
}")
</script>")
</div>")
You need to tell KendoUI to use the html elements as kendo controls.