Is it possible to override form helpers? - templates

Using the doc, I can set my own helper for the layout surrending my field, but I'd like to personalize also some fields given by play.
The main reason is for Twitter Bootstrap 2, where I need to change (in checkbox.scala.html)
#input(field, args:_*) { (id, name, value, htmlArgs) =>
<input type="checkbox" id="#id" name="#name" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
<span>#args.toMap.get('_text)</span>
}
to :
<label class="checkbox">
<input type="checkbox" name="#name" id="#id" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value)) />
#args.toMap.get('_text)
</label>
How can I do that ?
Thanks for your help!

I finally did it like this :
I created a package views.helpers.form, that contains :
bootstrap.scala.html :
#(elements: helper.FieldElements)
<div class="control-group#if(elements.hasErrors) { error}">
<label class="control-label" for="#elements.id">#elements.label(elements.lang)</label>
<div class="controls">
#elements.input
#elements.infos(elements.lang).map { info =>
<span class="help-inline">#info</span>
}
#elements.errors(elements.lang).map { error =>
<span class="help-block">#error</span>
}
</div>
checkbox.scala.html :
#**
* Generate an HTML input checkbox.
*
* Example:
* {{{
* #checkbox(field = myForm("done"))
* }}}
*
* #param field The form field.
* #param args Set of extra HTML attributes ('''id''' and '''label''' are 2 special arguments).
* #param handler The field constructor.
*#
#(field: play.api.data.Field, args: (Symbol,Any)*)(implicit handler: helper.FieldConstructor, lang: play.api.i18n.Lang)
#boxValue = #{ args.toMap.get('value).getOrElse("true") }
#helper.input(field, args:_*) { (id, name, value, htmlArgs) =>
<label class="checkbox">
<input type="checkbox" id="#id" name="#name" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
#args.toMap.get('_text)
</label>
div>
</div>
And in my template, all I have to do is :
#import helper.{FieldConstructor, inputText, inputPassword} #** Import the original helpers *#
#import helpers.form.checkbox #** Import my helpers *#
#implicitField = #{ FieldConstructor(helpers.form.bootstrap.f) }
And voilĂ ! It works!

It will be simpler to just write your own tag with the code you want and use it instead of the provided helper. It will simplify potential issues related to overwritting platform tags.

Related

why Show data in Angle brackets 'example',) in Django Form

HTML CODE
{% csrf_token %}
<input type="text" name="sub1" value="{{sub1}}" placeholder="Sub 1">
<input type="text" name="sub2" value="{{sub2}}" placeholder="Sub 2">
<input type="text" name="sub3" value="{{sub3}}" placeholder="Sub 3">
<input type="text" name="sub4" value="{{sub4}}" placeholder="Sub 4">
<input type="text" name="sub5" value="{{sub5}}" placeholder="Sub 5">
<button type="submit">SUBMIT</button>
</form>
VIEWS FUNCTION
def Contact(request):
data= {}
try:
if request.method=="POST":
sub1= request.POST.get('sub1'),
sub2= int(request.POST.get('sub2')),
sub3= int(request.POST.get('sub3')),
sub4= int(request.POST.get('sub4')),
sub5= int(request.POST.get('sub5')),
Total_num = sub1+sub2+sub3+sub4+sub5
print(sub1)
data = {
'Total_num':Total_num,
'sub1':sub1
}
except:
pass
return render(request,"contact.html",data)
OUTPUT
{{sub1}}
Result
('ad',)
You should remove the trailing commas: by the comma at the end, you wrap the value in a singleton tuple. By removing the comma, you get the real value, so:
sub1 = request.POST.get('sub1')
sub2 = int(request.POST.get('sub2'))
sub3 = int(request.POST.get('sub3'))
sub4 = int(request.POST.get('sub4'))
sub5 = int(request.POST.get('sub5'))
Total_num = sub1+sub2+sub3+sub4+sub5

How to use if statments to run second function Google script

I am trying to speed up my script, right now I currently have it set up so that on a button click a custom dialog (HTML) appears asking some questions. On submit, it calls out a gs function to pull the info back as variables. Depending on the first answer I have a series of If statments that trigger. Each of them pull up a different template, make a copy, populate some cells, emails it to you, and then dumps the data into a tracker. Each of them are different so the script is rather long - is there a way to have each if statment its own function? Would this even help the speed? I am new to scripting so any feedback is appreciated. Below is the Code and HTML
function onOpen() //adds option to top row in case buttons are not working.
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Create Doc.')
.addItem('Create Tracked Document', 'addItem')
.addToUi();
}
function addItem()//starts the initiation process
{
var html = HtmlService.createTemplateFromFile('form')
.evaluate()
.setWidth(300)
.setHeight(550);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Create New Document');
}
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
var Newform2= templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform2);
var dropSheet = qs.getSheetByName("blank");
var URL3 = Newform2.getUrl();
dropSheet.getRange("i8").setValue(title);
dropSheet.getRange("bc5").setValue(now);
dropSheet.getRange("b5").setValue(platform);
dropSheet.getRange("p5").setValue(area);
dropSheet.getRange("x5").setValue(rota);
dropSheet.getRange("al5").setValue(works);
dropSheet.getRange("at6").setValue(name);
NewOPLPOA.setSharing(DriveApp.Access.DOMAIN,DriveApp.Permission.COMMENT);
NewOPLPOA.setOwner("ME");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
}
else if (form_data.Document_Type == "Text1"){
var dumpfolder = DriveApp.getFolderById("abcd")
var templateSheet = DriveApp.getFileById("bgtrd");
var Newform1 = templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform1);
var dropSheet = qs.getSheetByName("DOC1");
var URL4 = Newform1.getUrl();
dropSheet.getRange("aa3").setValue(platform);
dropSheet.getRange("ah3").setValue(area);
dropSheet.getRange("ao3").setValue(works);
NewSEWO.setSharing(DriveApp.Access.DOMAIN, DriveApp.Permission.COMMENT);
NewSEWO.setOwner("Me");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL4]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL4);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL4, ui.ButtonSet.OK);
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
}
--HTML--
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myform">
<div class="form-group">
<label for="Document_Type">Document Type</label>
<select class="form-control" id="Document_Type" name = "Document_Type" required="required">
<?
var SS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Set Up");
var Avals = SS.getRange("A2:A").getValues();
var numberOfValues = Avals.filter(String).length;
var RangeVals = SS.getRange(2,1,numberOfValues).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeVals.length; ++i) { ?>
<option><?!= RangeVals[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for ="Name">Your Name</label>
<select class="form-control" name='Name' id="Name" required="required">
<?
var AvalN = SS.getRange("E2:E").getValues();
var numberOfValuesN = AvalN.filter(String).length;
var RangeValsN = SS.getRange(2,5,numberOfValuesN).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsN.length; ++i) { ?>
<option><?!= RangeValsN[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Platform">Platform</label>
<select class="form-control" id="Platform" name = "Platform" required="required">
<?
var AvalP = SS.getRange("C2:C").getValues();
var numberOfValuesP = AvalP.filter(String).length;
var RangeValsP = SS.getRange(2,3,numberOfValuesP).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsP.length; ++i) { ?>
<option><?!= RangeValsP[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Area">Area</label>
<select class="form-control" id="Area" name = "Area" required="required">
<?
var AvalA = SS.getRange("D2:D").getValues();
var numberOfValuesA = AvalA.filter(String).length;
var RangeValsA = SS.getRange(2,4,numberOfValuesA).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsA.length; ++i) { ?>
<option><?!= RangeValsA[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="Rotation">Rotation</label>
<select class="form-control" name='Rotation' id="Rotation">
<?
var AvalR = SS.getRange("F2:F").getValues();
var numberOfValuesR = AvalR.filter(String).length;
var RangeValsR = SS.getRange(2,6,numberOfValuesR).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsR.length; ++i) { ?>
<option><?!= RangeValsR[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="WorkSt">Work Station</label>
<input type='text' name='WorkSt' id="WorkSt" />
</div>
<div class="block form-group">
<label for="Title">Title</label>
<input type='text' name='Title' id="Title" required="required"/>
</div>
<div class="block">
<button type="submit" class="action">Submit</button>
</div>
</form>
<script>
document.querySelector("#myform").addEventListener("submit",
function(e)
{
e.preventDefault(); //stop form from submitting
google.script.run.addNewItem(this);
google.script.host.close();//close this dialogbox
}
);
</script>
</body>
</html>
is there a way to have each if statement its own function?
For visibility purposes, you certainly can modify your code as
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
function1();
}
else if (form_data.Document_Type == "Text1"){
function2();
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
function function1(){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
...
}
function function2(){
var dumpfolder = DriveApp.getFolderById("abcd")
...
}
Would this even help the speed?
Not really. To help up speed, you should rather try to implement Best Practices.
In particular: Reduce repeated calls to external services, including SpreadsheetApp.
For example, try to position the cells to which you want to assign values into an adjacent range, so you can use the method setValues() instead of multiple setValue() and thus make your code more efficient.
Sample:
var range = dropSheet.getRange("I8:N8");
var values = [];
values[0] = [];
values[0].push(title, now, platform, area, rota, works, name);
range.setValues(values);
Also, try to avoid repeating the same request for each if condition and rather make a single request after exiting the if statement, e.g. for:
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
I hope this helps!

Can i user pattern in #Html.Editor In MVC?

we can use pattern(regex) for inputs control
like that :
<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
My question is can i user Pattern in #html.Editor ?
I tried to use this way:
#Html.Editor("country_code", null, new { htmlAttributes = new { #class = "form-control" , required = "required" , pattern="[A-Za-z]{3}"} })
But pattern="[A-Za-z]{3}" does not recognize

Google Polymer: google-map-search doesn't work

<paper-dialog id="post" entry-animation="scale-up-animation" exit-animation="fade-out-animation">
<div class="find-area">
<paper-textarea on-input="find" id="find_textarea" class="find-place-text" label="Find your place" maxlength="250"></paper-textarea>
</div>
<div class="map-area">
<google-map id="[[map]]"
api-key="000000000myapi000000"
latitude="[[lat]]"
longitude="[[lon]]"
fit-to-markers>
</google-map>
<google-map-search id="google_search"
globalSearch="true"
map="[[map]]"
results="[[results]]">
</google-map-search>
</div>
<paper-button on-tap="[[upload]]">Accept</paper-button>
<label>coords:[[ results::lat ]], [[ results::lon ]]</label>
<label>query:[[ query ]]</label>
<label>map:[[ map ]]</label>
<label>results:[[results]]</label>
</paper-dialog>
<script>
function _showPosition(position) {
try {
x.latitude = position.coords.latitude;
x.longitude = position.coords.longitude;
}catch (err){
alert(err+'; position:'+position)
}
}
function showError(error) {
alert('error:'+ error)
}*/
function _submit(event) {
Polymer.dom(event).localTarget.parentElement.submit();
}
Polymer({
is: 'profile-new-post',
properties: {
enable : {
type: Boolean,
value: true
},
lat : {
value : 37.77493
},
lon : {
value : -122.41942
},
query : {
type : String,
value : ""
},
results : {
type : Array
},
map : {
type : Object
}
},
func : function (e) {
this.map = this.$.map;
post.open();
},
find : function (e) {
this.$.google_search.query = this.$.find_textarea.value;
this.query = this.$.google_search.query;
this.$.google_search.search();
this.lat = this.$.google_search.results.latitude;
this.lon = this.$.google_search.results.longitude;
//alert(this.$.google_search.results.latitude + '; ' + this.$.google_search.results.longitude)
},
I'm trying to use [[]] brackets because of django use {{}}. Map, results and coords are empty at output lables. It shows map with San Francisco but when i try to print text in input it doesn't want to search. The aren't any errors in console. I've saw tutorial video from google about this, but there was old version of Polymer and many things like {{ $.element.atribute }} inside element head doesn't work (it doesn't know what '$' is). Maybe someone can explain for me what's the biggest difference between [[ ]] and {{ }}, because i can't understand it from official tutorial?
Solve: to solve it, i must put source from inside dialog to new template with property is="dom-bind.
<p><paper-button raisedButton on-tap="upload">Upload</paper-button></p>
<paper-button id="dialogbutton" on-tap="func">Post</paper-button>
<paper-dialog id="post" entry-animation="scale-up-animation" exit-animation="fade-out-animation">
<template is="dom-bind">
<div class="find-area">
<paper-input value="{{ input_query }}" on-input="find" id="find_textarea" class="find-place-text" label="Find your place" maxlength="250"></paper-input>
</div>
<div class="map-area">
<google-map-search
id="google_search"
map="{{ map }}"
query="{{ input_query }}"
results="{{results}}"
on-google-map-search-results="searchingComplite">
</google-map-search>
<google-map
map="{{map}}"
latitude="{{results[0}.latitude}}"
longitude="{{results[0}.longitude}}">
</google-map>
</div>
<paper-button on-tap="upload">Accept</paper-button>
<label>coords:{{ lat }}, {{ lon }}</label>
<label>query:{{ query }}</label>
<label>map:{{ map }}</label>
<label>results:{{ results }}</label>
</template>
There are a couple of issues here:
Yes, the [[]] brackets are the problem here because they enforce one-way binding. That means that the results from the google-map-search can't propagate upwards and the labels are empty. You need to change the results=[[results]] to results={{results}} to enable two-way binding
For declerative event handlers, you don't need any brackets. So this line <paper-button on-tap="[[upload]]">Accept</paper-button> should be ?<paper-button on-tap="upload">Accept</paper-button>
To access sub-properties of an data bound object you need to use dot notation (.). This line <label>coords:[[ results::lat ]], [[ results::lon ]]</label> should be changed to <label>coords:[[ results.lat ]], [[ results.lon ]]</label>
I would also change lat and lon to computed properties which either return default values (alternatively just use attributes on your google-map element for that) or the values from your search result.

Angularjs filter unordered list

I'm trying to filter strings in a static unordered list. I'm able to filter items in an array but not sure how to do it for static html content.
The way I've learned to achieve it using an array is by using this method:
<input type="search" ng-model="name" />
<ul>
<li ng-repeat="person in people | filter:name">
{{ person }}
</li>
</ul>
I'm trying to achieve the same effect using an existing <ul>
<input type="search" ng-model="filter.name" placeholder="filter..." />
<ul>
<li>Bob/li>
<li>Lisa</li>
<li>Lewis</li>
<li>Xuemin</li>
<li>Tom</li>
<li>Cassidy</li>
</ul>
I want to be able to filter the list items based on the text strings inside them, so for example typing 'L' in the textbox would only show:
Lisa
Lewis
Here is a hacked out way of doing it JSFiddle.
The key to it is in ng-change="filter()". Every time you enter a letter you decide which elements to show or hide.
$scope.filter = function() {
var elem = document.getElementById('list');
for (var i = 0; i < elem.children.length; i++) {
var name = elem.children[i].children[0].innerHTML;
if (name.indexOf($scope.name) != -1 || $scope.name == "") {
elem.children[i].style.display = "block";
} else {
elem.children[i].style.display = "none";
}
}
}
Like I said, it's an ugly hack, but it works. You would be better off making an object out of your names, and using ng-repeat.