Getting the FormController of a form - angularjs-directive

I have code like this in my controller:
var forms = $('form'); // my selector is a bit more complex.
var form = forms[0];
This gives me the form. From this how do I get hold of the FormController so that I can check on properties like $pristine, $invalid, etc.?
var formController = // how to get this from form?
var ispristine = formController.$pristine;
I actually have multiple child forms and I will have to get the pristine state of them all.
Thanks

I figured that you can do this to get hold of the "FormController" properties of a form:
// Get hold of the form in your DOM
var forms = $('form');
var form = forms[0];
// Get hold of the form's scope object, which is injected with an object containing these properties.
// Note that 'formName is the name of the form element in html. (<form name='formName'>....</form>
var formScope = $(form).scope().formName;
var ispristine = formScope.$pristine;
Note that this works only if the form element has a name attribute!

Related

How can I add choices in a Google Form with Google Apps Script

I'm trying to master creating Google Forms programmatically, but can't assign choices to a multiple-choice item. I can create the item (testQuestion) and give it a title, but my createChoice() statements don't add choices.
Here's my code, based on https://developers.google.com/apps-script/reference/forms/page-navigation-type
function testCreateChoices() {
/* modification of
testPageNavigation()
to see how to import choices from a range on sheet
*/
// Create a form
var form = FormApp.create('createChoice Test');
// add a multiple-choice item
var testQuestion = form.addMultipleChoiceItem();
testQuestion.setTitle('Anything here?');
var whatsis = testQuestion.createChoice('bozzle');
var firstChoice = testQuestion.createChoice('this');
testQuestion.createChoice("that");
testQuestion.createChoice("the other");
testQuestion.createChoice("Ouch!");
//add a new multiple-choice item and a pagebreak item
var item = form.addMultipleChoiceItem();
var pageBreak = form.addPageBreakItem();
// Set some choices with go-to-page logic.
var rightChoice = item.createChoice('Vanilla', FormApp.PageNavigationType.SUBMIT);
var wrongChoice = item.createChoice('Chocolate', FormApp.PageNavigationType.RESTART);
// For GO_TO_PAGE, just pass in the page break item. For CONTINUE (normally the default), pass in
// CONTINUE explicitly because page navigation cannot be mixed with non-navigation choices.
var iffyChoice = item.createChoice('Peanut', pageBreak);
var otherChoice = item.createChoice('Strawberry', FormApp.PageNavigatio[enter image description here][1]nType.CONTINUE);
item.setChoices([rightChoice, wrongChoice, iffyChoice, otherChoice]);
}
Here's what I get, with the choices "bozzle" and so on not displayed, and an image of what I want but can't create.
Many thanks for any help!
Here's a screenshot, with no labels/choices under "Anything here?"
And a mockup with "bozzle", "this" and so on as choices
The reason you are not seeing the options for the testQuestion is because you didn't set the choices for the question.
Therefore, I suggest you update the bit where you create your first question to this:
var testQuestion = form.addMultipleChoiceItem();
testQuestion.setChoices([testQuestion.createChoice('bozzle'), testQuestion.createChoice('this'), testQuestion.createChoice("that"), testQuestion.createChoice("the other"), testQuestion.createChoice("Ouch!")]);
The createChoice method is used to create the choice items only and in order to actually add them to the question, you have to use the setChoices method as well.
Reference
Apps Script Class MultipleChoiceItem - createChoice(value);
Apps Script Class MultipleChoiceItem - setChoices(Choice).

Apps Script - Get existing ListItem on FormApp

I'm trying to populate a ListItem inside a Form whith data from a SpreadSheet. Each row would be a choice.
So I have a ListItem question in my form and what I couldn't find out is: How can I acess an existing instance of a ListItem question in a form?
I have a : var form = FormApp.getActiveForm();, but how can I do something like "getFormAppListItem()"
And another doubt I have is... If I create a ListItem inside my function (addListItem() method), will it be recreated everytime someone opens the form (is a public survey)?
var field1 = SpreadsheetApp.openById("XXXXXXXXXXXXXXXXXXXX").getSheetByName("Sheet1").getRange(2,1).getValue;
var field2 = SpreadsheetApp.openById("XXXXXXXXXXXXXXXXXXXX").getSheetByName("Sheet1").getRange(3,1).getValue;
var field3 = SpreadsheetApp.openById("XXXXXXXXXXXXXXXXXXXX").getSheetByName("Sheet1").getRange(4,1).getValue;
var form = FormApp.openById('1234567890abcdefghijklmnopqrstuvwxyz');
var item = form.addMultipleChoiceItem();
item.setTitle('Choose the Pet you prefer').setChoices([
item.createChoice(field1),
item.createChoice(field2)
item.createChoice(field3)
])
.showOtherOption(true);
Please see the details here https://developers.google.com/apps-script/reference/forms/multiple-choice-item. Hope this helps.

GAS - define listBox() displayed value

I have a form built and displayed in UiApp which uses the listBox class. My listBoxes are created as in the example below:
var yearText = app.createListBox().setName("yearText")
.addItem("")
.addItem("Reception")
.addItem("Nursery");
When the form loads for the first time they default to display blank (the value at index 0). What I am trying to do is reload the form with stored data, populating the listBox with it's saved value whilst still offering the same options as above (blank, Reception, Nursery).
I have tried using the various setValue methods available to the listBox class but I am not making any progress (variations of setValue are working fine for textArea, checkBox and dateBox classes elsewhere in the form). Any help or guidance gratefully received!
The method for that is setItemSelected(index,Boolean), example below
function doGet(){
var app = UiApp.createApplication();
var list = app.createListBox().addItem('').addItem('v2').addItem('v3').addItem('v4').setItemSelected(2,true);
app.add(list);
return app;
}
Or also : setSelectedIndex(index) (same link for doc
example below too
function doGet(){
var app = UiApp.createApplication();
var list = app.createListBox().addItem('').addItem('v2').addItem('v3').addItem('v4').setSelectedIndex(2);
app.add(list);
return app;
}

Multiple Page UI using UiService

I would like to use Google Apps Script UiService to produce a multiple page user interface.
Here's what I've got so far:
function doGet(e)
{
var app=UiApp.createApplication();
var nameLabel=app.createLabel('Name:');
var button=app.createButton("next");//my button on clicking,trying to divert to other UI
var handler=app.createServerHandler("myclick");
button.addClickHandler(handler);
app.add(namelabel);
app.add(button);
return app;
}
function myClick(){
//on clicking the button it should call the other ui or other html page
is there any method for that.}
How can I do this?
You should look at How To Allow Users to Review Answers before Submiting Form?, which has an example that does this.
The idea is to create your UiApp with multiple Panels, then show or hide them in response to user actions, using setVisible(). (If you were using the HtmlService, you would enclose your "pages" in different <div>s, and change their display attributes. See toggle show/hide div with button?.)
The Best Practices also describes use of client-side handlers for responsiveness, so let's try that.
/**
* Very simple multiple page UiApp.
*
* This function defines two panels, which appear to the end user
* as separate web pages. Visibility of each panel is set to
* control what the user sees.
*/
function doGet() {
var app = UiApp.createApplication();
var page1 = app.createFlowPanel().setId('page1');
var page2 = app.createFlowPanel().setId('page2');
// Content for Page 1
page1.add(app.createLabel('Page 1'));
var page1Button = app.createButton('Next Page');
page1.add(page1Button);
// Create client handler to "change pages" in browser
var gotoPage2 = app.createClientHandler()
.forTargets(page1).setVisible(false)
.forTargets(page2).setVisible(true);
page1Button.addClickHandler(gotoPage2);
// Content for Page 2
page2.add(app.createLabel('Page 2'));
var page2Button = app.createButton('Previous Page');
page2.add(page2Button);
// Create client handler to "change pages" in browser
var gotoPage1 = app.createClientHandler()
.forTargets(page1).setVisible(true)
.forTargets(page2).setVisible(false);
page2Button.addClickHandler(gotoPage1);
app.add(page1);
app.add(page2);
// Set initial visibility
page1.setVisible(true);
page2.setVisible(false);
return app;
}
That works for changing the view of the UI. To extend this for general purposes, you would likely want to add server-side handlers to the same buttons to perform work, and update the contents of the panels as things progress.
Here is working code
that demonstrates a multiple page form, i.e. it does the initial doGet() and then lets you advance back and forth doing multiple doPost()'s. All this is done in a single getForm() function called by both the standard doGet() and the doPost() functions.
// Muliple page form using Google Apps Script
function doGet(eventInfo) {return GUI(eventInfo)};
function doPost(eventInfo) {return GUI(eventInfo)};
function GUI (eventInfo) {
var n = (eventInfo.parameter.state == void(0) ? 0 : parseInt(eventInfo.parameter.state));
var ui = ((n == 0)? UiApp.createApplication() : UiApp.getActiveApplication());
var Form;
switch(n){
case 0: {
Form = getForm(eventInfo,n); // Use identical forms for demo purpose only
} break;
case 1: {
Form = getForm(eventInfo,n); // In reality, each form would differ but...
} break;
default: {
Form = getForm(eventInfo,n) // each form must abide by (implement) the hidden state variable
} break;
}
return ui.add(Form);
};
function getForm(eventInfo,n) {
var ui = UiApp.getActiveApplication();
// Increment the ID stored in a hidden text-box
var state = ui.createTextBox().setId('state').setName('state').setValue(1+n).setVisible(true).setEnabled(false);
var H1 = ui.createHTML("<H1>Form "+n+"</H1>");
var H2 = ui.createHTML(
"<h2>"+(eventInfo.parameter.formId==void(0)?"":"Created by submission of form "+eventInfo.parameter.formId)+"</h2>");
// Add three submit buttons to go forward, backward and to validate the form
var Next = ui.createSubmitButton("Next").setEnabled(true).setVisible(true);
var Back = ui.createSubmitButton("Back").setEnabled(n>1).setVisible(true);
var Validate = ui.createSubmitButton("Validate").setEnabled(n>0).setVisible(true);
var Buttons = ui.createHorizontalPanel().add(Back).add(Validate).add(Next);
var Body = ui.createVerticalPanel().add(H1).add(H2).add(state).add(Buttons).add(getParameters(eventInfo));
var Form = ui.createFormPanel().setId((n>0?'doPost[':'doGet[')+n+']').add(Body);
// Add client handlers using setText() to adjust state prior to form submission
// NB: Use of the .setValue(val) and .setValue(val,bool) methods give runtime errors!
var onClickValidateHandler = ui.createClientHandler().forTargets(state).setText(''+(parseInt(n)));
var onClickBackHandler = ui.createClientHandler().forTargets(state).setText(''+(parseInt(n)-1));
Validate.addClickHandler(onClickValidateHandler);
Back.addClickHandler(onClickBackHandler);
// Add a client handler executed prior to form submission
var onFormSubmit = ui.createClientHandler()
.forTargets(state).setEnabled(true) // Enable so value gets included in post parameters
.forTargets(Body).setStyleAttribute("backgroundColor","#EEE");
Form.addSubmitHandler(onFormSubmit);
return Form;
}
function getParameters(eventInfo) {
var ui = UiApp.getActiveApplication();
var panel = ui.createVerticalPanel().add(ui.createLabel("Parameters: "));
for( p in eventInfo.parameter)
panel.add(ui.createLabel(" - " + p + " = " + eventInfo.parameter[p]));
return panel;
}
The code uses a single "hidden" state (here visualized in a TextBox) and multiple SubmitButton's to allow the user to advance forward and backward through the form sequence, as well as to validate the contents of the form. The two extra SubmitButton's are "rewired" using ClientHandler's that simply modify the hidden state prior to form submission.
Notes
Note the use of the .setText(value) method in the client handler's. Using the Chrome browser I get weird runtime errors if I switch to either of the TextBox's .setValue(value) or .setValue(value, fireEvents) methods.
I tried (unsuccessfully) to implement this logic using a Script Property instead of the hidden TextBox. Instead of client handlers, this requires using server handlers. The behavior is erratic, suggesting to me that the asynchronous server-side events are occurring after the form submission event.
You could load different UI's on reading the parameters in your app.
The doGet(e) passes the parameters in the app's url. This way you could call your app with for example: ?myapp=1 (url parameter).
in your doGet you could read that parameter with: e.parameter.myapp
This way you could load different applications depending on the parameters that where passed.
You could just change your button with a link (to your own app, with different url parameters).
You could also do it with buttons and handlers but the above way has my preference.
If you want to use a button<>handler just change you main (first panel) and each time add a completely new panel to your app object. This way you would start from scratch (i.e. create a new application).

handler design for dynamically created listboxes

I'm trying to make a UI that allow users to select an action for each agenda item in a spreadsheet. After a user select an action, I would like to update the spreadsheet with the selection. Since the data in the spreadsheet are not static, the UI was written dynamically.
This is how I created the listboxes :
// add labels and a drop down box of actions for each agenda item mark for today
for (i = 0; i < labels.length; i++) {
// labels is an array of objects
var topic = labels[i]['topic'];
// add label to grid
myGrid.setWidget(i, 0, myApp.createLabel(topic));
// the id of each listbox is the content of its corresponding label
var id = ObjApp.camelString(topic)
var lboxActions = myApp.createListBox().setId(id);
//add items to listbox
lboxActions.addItem('Select');
lboxActions.addItem('Add to agenda');
lboxActions.addItem('Move to another meeting');
lboxActions.addItem('Move to a special meetin');
lboxActions.addItem('Move to email');
//add drop down list to grid
myGrid.setWidget(i, 1, lboxActions);
}
I have 3 questions:
1) Which is a better design?
a) Design 1: a save button next to each listbox.
b) Design 2: one submit button at the bottom to save every entry
2) How would I collect information on what the user select? How would I write such handlers? I added the following code for each design but I don't think I'm doing it right.
a) Design 1: the following lines of code were added to the for loop described above
var buttonSave = myApp.createButton('Save');
myGrid.setWidget(i, 2, buttonSave);
var handlerSelection = myApp.createServerHandler('selectAction');
handlerSelection.addCallbackElement(mainPanel);
buttonSave.addClickHandler(handlerSelection);
b) Design 2: the following lines of code were added outside the for loop
//update spreadsheet when user click "submit"
var handlerUpdate = myApp.createServerHandler('responseToSubmit');
handlerUpdate.addCallbackElement(mainPanel);
buttonSubmit.addClickHandler(handlerUpdate);
mainPanel.add(myGrid);
mainPanel.add(buttonSubmit);
myApp.add(mainPanel);
3) How do I write functions for the handlers? These are not correct because I wasn't able to extract the information from the list boxes.
a) Design 1
function responseToSave(e) {
var name = e.parameter.source;
var selection = e.parameter.name;
var selectionObj = new Object();
selectionObj['status'] = selection;
selectionObj['name'] = name;
choicesMade.push(selectionObj)
Logger.log(choicesMade);
return choicesMade;
}
b) Design 2
function responseToSubmit(e) {
var myApp = UiApp.getActiveApplication();
for (i=0; i < labels.length; i++) {
var lboxId = ObjApp.camelString(labels[i]['topic']);
//[EDIT] e.parameter.lboxId would not work because lboxId is a string
var selection = e.parameter[lboxId];
choicesMade[labels[i]] = selection;
}
Logger.log(choicesMade);
return choicesMade;
}
Thanks
Q1:
The design purely depends on what your application is intended to do and how your users use it. There is no 'better' design - each of them has its own pros and cons and the choice would be based on how your app is used.
However, do also consider Design 3 which is saving the changes when the dropdown box is changed. It will be one click less for the user
Q2 and Q3:
You should use the setName on the listBox
var lboxActions = myApp.createListBox().setId(id).setName(id);
I generally use the same string for the id and the name to avoid confusion, but you should use setName
After that you can access the item selected in the handler function as
e.parameter.id
Finally, on buttonSave, you should use the addClickHandler instead of addChangeHandler.