Square sq-payment-form Money amount not populating - square-connect

the example form(C#), sq-payment-form hard codes the amount to charge as
Money amount = new Money(100, Money.CurrencyEnum.USD); I believe I need to change the 100 to reference the charge value in the form. however, I can't find any information on how to accomplish.
I have added a field to the form id "tc"
<div class="sq-field">
<label class="sq-label sq-field--in-wrapper">Total Charge</label>
<input class="sq-field" type="text" id="tc" />
<div id="sq-amount"></div>
</div>
and put an alert in the .js file to display tc.value
i see the value in the alert but in the onpost method i cannot seem to reference the field using response.form("tc")
I have tired referencing both
string tcharge = Request.Form["sq-amount"].;
string tcharge = Request.Form["tc"]();
to no avail..... all the examples on the square site i have found hard code the charge amount. one of the examples on the Square site actually has a comment as follows;
"// Monetary amounts are specified in the smallest unit of the applicable currency.
// This amount is in cents. It's also hard-coded for $1.00,
// which isn't very useful.
Money amount = new Money(100, Money.CurrencyEnum.USD);"
what am I missing
both the form objects are null so the transaction fails. I am fairly new to C# and would appreciate any assistance.

If you're wanting the customer to be able to enter a value and pass it to your backend to charge, you would just need to implement another form field (like the hidden card nonce). For example:
<input type="text" name="sq-amount">
When the form is submitted, you would be able to retrieve the value that was entered like you have above (you would probably want to add in some checks to ensure it's a valid amount etc):
string tcharge = Request.Form["sq-amount"].;
...
Money amount = new Money(Int32.Parse(tcharge), Money.CurrencyEnum.USD);"

Related

How to populate select fast and only once

I have over 3200 rows in a Google Sheet. I need a dropdown with each value on a web app.
I have this in Apps Script:
function doGet(e) {
var htmlOutput = HtmlService.createTemplateFromFile('CensusWebApp2');
var streets = getStreets();
var businessNames = getbusinessNames();
htmlOutput.message = '';
htmlOutput.streets = streets;
htmlOutput.businessNames = businessNames;
return htmlOutput.evaluate();
}
function getbusinessNames(){
var ss= SpreadsheetApp.getActiveSpreadsheet();
var StreetDataSheet = ss.getSheetByName("businessNames");
var getLastRow = StreetDataSheet.getLastRow();
var return_array = [];
return_array= StreetDataSheet.getRange(2,1,getLastRow-1,1).getValues();
return return_array;
}
This is the HTML code
<select type="select" name="IntestazioneTari" id="IntestazioneTari" class="form-control" >r>
<option value="" ></option>
<? for(var i = 0; i < businessNames.length; i++) { ?>
<option value="<?= businessNames[i] ?>" ><?= businessNames[i] ?></option>
<? } ?>
</select><be>
I'm creating an app similar to surveys forms, but this dropdown will be the same for every entry.
Is there a way to load this only once and not every time the form is submitted and got again for a new survey entry? (from the same operator/device)
I believe your goal as follows.
You want to use the value of businessNames retrieved from Google Spreadsheet at HTML side.
The value of businessNames is not changed. So you want to load the value only one time.
In this case, how about declaring the value in the tag of <script> as a global? When this point is reflected to your script it becomes as follows.
Modified script:
In this case, your HTML side is modified.
<select type="select" name="IntestazioneTari" id="IntestazioneTari" class="form-control" >r>
<option value="" ></option>
<? for(var i = 0; i < businessNames.length; i++) { ?>
<option value="<?= businessNames[i] ?>" ><?= businessNames[i] ?></option>
<? } ?>
</select>
<input type="button" value="ok" onclick="test()">
<script>
const value = JSON.parse(<?= JSON.stringify(businessNames) ?>); // Here, the value of "businessNames" is retrieved.
function test() {
console.log(value);
}
</script>
In this modification, when the HTML is loaded, the value of businessNames is added to the HTML by evaluate() method. At that time, businessNames is given to HTML and Javascript. By this, const value = JSON.parse(<?= JSON.stringify(businessNames) ?>); has the value of businessNames. In order to confirm this value, when you click a sample button of <input type="button" value="ok" onclick="test()">, you can see the value at the console. By this, you can use the value of businessNames at the Javascript side after HTML is loaded.
Reference:
HTML Service: Templated HTML
As the values from the spreadsheet won't change, I created a really long text row with all the options and pasted them directly in the HTML.
I made the same with the other information. Load time decreased enormously.
This is the code I use to generate the values:
return_array= "<option>" + businessNamesSheet.getRange(2,1,getLastRow-1,1).getValues().join("</option><option>")+"</option>";
We are talking about performance, and there are 3 things you need to do when doing so:
Make measurements
Make measurements again
And make some more measurements
A change in the code could have a negative impact for a reason that you didn't expect (it's hard to keep every single little detail in mind). When making a Google Apps Script web app, you have 3 reported times:
The timings in your browser. How much did it really take to load the entire page
The running time on Google Apps Script execution log.
Small timing inside your application using console.time (reference), console.timeLog (reference) and console.timeEnd (reference) (collectively called console timers).
Note that the first 2 may change without you changing a thing, probably because of the inner working in Google.
So let's start doing what I said: measuring. I'd measure:
The entire doGet function
The getStreets()
The getbusinessNames()
The template.evaluate()
How much time it takes to load the page (browser)
This will give me a rough idea on what takes most of the time. Knowing that, you can try the following ideas.
Note that I don't have your code so I can't tell how it will effect your times, so your mileage may vary. Also note that most ideas could be implemented simultaneously, this doesn't mean it's a good idea and can even slow what a single idea could have achieved.
Idea 1: Copy the generated options into the template
If you don't need to load the options from somewhere (like I suppose you are doing), you could generate the template once, copy the generated options and paste it to the HTML. This will obviously avoid the problem of having the request the list of options and evaluating them every time, but you lose flexibility.
Idea 2: Having the options in code instead of somewhere else
If the options won't change or you will be changing them, you could add them into your code:
const BUSINESS_NAMES = `
business 1
hello world
another one
and another one
`
function getbusinessNames() {
return BUSINESS_NAMES
.split('\n')
.filter(v => !!v) // remove empty string
}
It's similar to idea 1 but it's easier to change the values when needed, specially when using the V8 support for multi line strings.
Idea 3: Use a Google Apps Script cache
If what's taking time is querying the options, you could use CacheService (see reference). This would allow you to only query the options every X seconds (up to 6 hours) instead of every time.
function doGet(e) {
// [...]
const cache = CacheService.getScriptCache()
let businessNames = cache.get('businessNames')
if (businessNames == null) {
businessNames = getbusinessNames()
cache.put('businessNames', businessNames, 6*60*60)
}
// use businessNames
// [...]
}
In this case I've only done it with businessName but it can also be use in streets.
having a 6 hour cache means that it could take up to 6 hours for a change in the list to propagate. If you add the options manually you could add a function to force the reloading it:
function forcecacheRealod() {
cache.put('streets', getStreets(), 6*60*60)
cache.put('businessNames', getbusinessNames(), 6*60*60)
}
Idea 4: Improve how you load the data
Is very common for new Google Apps Script users to iterate the rows one by one getting the value. It's way more efficient to get the proper range with all the rows and columns and call getValues (reference).
Idea 5: do a fetch instead of submitting the form
If what is happening is that it takes time to load after sending the data, it might be a good idea to use google.script.run (reference) instead of making a form and submitting it, since it could prevent reloading the entire page again.
Idea 6: SPA web app
The result of doubling down on the last idea. Same benefits and you could load the necessary data in the background while the user lands on the home page.
Idea 7: Load the options dynamically
Use google.script.run (reference) to load the options once the page has already been loaded. May actually be slower but you can give faster feedback to the user.
Idea 8: Save the options in localStorage
Requires idea #7. Save the dynamically loaded options into localStorage(see reference) so the user only needs to wait once. You may need to load them once in a while to make sure they are up-to-date.
References
Console timer (MDN)
CacheService (Google Apps Script reference)
Range.getValues() (Google Apps Script reference)
Class google.script.run (Client-side API) (Google Apps Script reference)
Window.localStorage (MDN)

Adding a deform form in an existing page (mako template) validator not called?

I have an existing (WIP) pyramid project, with the simplistic forms all being done by hand. As the user requirements have been steadily increasing in complexity, I wanted to integrate deform forms to simplify my own maintenance/programming tasks.
My initial test was to try for an interfield form[1], the purpose being to ensure that a certain date predates another date in the form. Here's the simplified definition for the schema and validator:-
class Schema(colander.MappingSchema):
startdate = colander.SchemaNode(colander.Date())
enddate = colander.SchemaNode(colander.Date())
def validator(form, value):
if value['enddate'] - value['startdate'] < 0:
exc = colander.Invalid(form, 'Start date must precede End date')
exc['enddate'] = 'Must be after %s' % value['startdate']
raise exc
schema = Schema(validator=validator)
form = deform.Form(schema, buttons=('submit',))
I then pass the form to my mako template and call:-
${form.render() | n}
This renders the form properly, and my date selectors work (of course, after I had to mess around with loading the correct CSS and javascripts). However clicking submit doesn't do any validation (not even the basic 'you didn't enter a value'), instead it goes right back to my view_config.
What could I be missing?
[1] - https://deformdemo.pylonsproject.org/interfield/
It turns out deform doesn't handle the validation automatically, and I have to actually call validate, something like below:-
try:
appstruct = form.validate(request.POST.items())
except deform.ValidationFailure as e:
return {'form': e.render()}

three dependent drop down list opencart

I want to make 3 dependents drop down list, each drop down dependent to the previous drop down, so when I select an item from first drop down , all data fetch from database and add to second drop down as item.
I know how to do this in a normal php page using ajax, but as opencart uses MVC I don't know how can I get the selected value
Basically, you need two things:
(1) Handling list changes
Add an event handler to each list that gets its selected value when it changes (the part that you already know), detailed tutorial here in case someone needed it
Just a suggestion (for code optimization), instead of associating a separate JS function to each list and repeating the code, you can write the function once, pass it the ID of the changing list along with the ID of the depending list and use it anywhere.
Your HTML should look like
<select id="list1" onchange="populateList('list1', 'list2')">
...
</select>
<select id="list2" onchange="populateList('list2', 'list3')">
...
</select>
<select id="list3">
...
</select>
and your JS
function populateList(listID, depListID)
{
// get the value of the changed list thorugh fetching the elment with ID "listID"
var listValue = ...
// get the values to be set in the depending list through AJAX
var depListValues = ...
// populate the depending list (element with ID "depListID")
}
(2) Populating the depending list
Send the value through AJAX to the appropriate PHP function and get the values back to update the depending list (the part you are asking for), AJAX detailed tutorial here
open cart uses the front controller design patter for routing, the URL always looks like: bla bla bla.bla/index.php?route=x/y/z&other parameters, x = folder name that contains a set of class files, y = file name that contains a specific class, z = the function to be called in that class (if omitted, index() will be called)
So the answer for your question is:
(Step 1) Use the following URL in your AJAX request:
index.php?route=common/home/populateList
(Step 2) Open the file <OC_ROOT>/catalog/controller/common/home.php , you will find class ControllerCommonHome, add a new function with the name populateList and add your logic there
(Step 3) To use the database object, I answered that previously here
Note: if you are at the admin side, there is a security token that MUST be present in all links along with the route, use that URL:
index.php?route=common/home/populateList&token=<?php echo $this->session->data['token'] ?> and manipulate the file at the admin folder not the catalog
P.S: Whenever the user changes the selected value in list # i, you should update options in list # i + 1 and reset all the following lists list # i + 2, list # i + 3 ..., so in your case you should always reset the third list when the first list value is changed
P.P.S: A very good guide for OC 1.5.x => here (It can also be used as a reference for OC 2.x with some modifications)

MaxLength attribute and unobtrusive validation

If I add a MaxLengthAttribute to a property like this:
[MaxLength]
[DataType(DataType.MultilineText)]
public string Notes { get; set; }
The markup is rendered like this:
<textarea class="form-control" data-bind="value: Notes" data-val="true" data-val-maxlength="The field Notes must be a string or array type with a maximum length of '-1'." data-val-maxlength-max="-1" id="Notes" name="Notes"></textarea>
and the validation result looks something like this:
This is obviously not the intended result. The text area should allow A LOT more characters than '-1'.
I can think of multiple ways of addressing this (e.g. removing the attribute via jQuery, manually updating the rule with javascript, etc).
What is the most elegant way of addressing this issue? Is this a bug with MVC/Validator
You are not specifying the desired maximum length of the string, what do you expect? This overload of the MaxLength attributes takes an integer as argument which specifies the actual maximum allowed length of the string. When you use the parameter-less constructor it will use the maximum length allowed by the database, not sure why jQuery Validation chose to implement this as -1 though.

Looking for a easier cleaner way to save ajax POST data to a django model and avoid hardcoding for saving?

I have been working on a django project that requires a large amount of user input and processing and am sick of hardcoding the data in the view in order to save it to my models as seen below.
mymodel = TheModel.objects.get(id=model.id)
mymodel.name = request.POST.get('name')
mymodel.zip = request.POST.get('zip')
...
mymodel.save()
Except instead of two model attributes like I used above there are sometimes up to 25 that need to be saved.
I am using ajax to serialize the forms and send them to my views where they are saved. I am looking for the cleanest way possible to get around this problem. Less code the better and I am willing to reformat my models if there is a way that significantly shortens the number of lines of code I have now.
Thanks
you may want to have a look at ModelForms
This method will work, although you have to be careful to add a model field / ajax parameter at the sametime for it to work
Given:
Form1
<form method="post">
<input name="parameter1" />
<input name="parameter2" />
<input name="parameter3" />
</form>
Write javascript code so the data going across the wire looks like this JSON (form serialization
will probably not work)
{ parameter1 : "some data", "parameter2" : "some data", parameter3 : "some data" }
Then, you have a django model that looks like this
class MyModel(models.Model):
parameter1 = models.StringField()
parameter2 = models.StringField()
parameter3 = models.StringField()
You can save/update with code like this:
params = dict(request.POST)
m = MyModel.objects.create(**params)
or
m = MyModel.objects.get(id=ID)
m.update(force_update=False,**params)
If your parameters do not line up the code will fail though.

Resources