web2py - Dropdown menu - database

I'm trying to have a dropdown menu for the user to select the database table. I have defined few tables in db.py and I want the user the to select a particular table from a dropdown menu and insert entries. Right now I use SQLFORM:
def index():
form=SQLFORM(db.selectedtable) #want to change the table name#
if form.process().accepted:
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill out the form'
return dict(form=form)
I need the user to select 'selectedtable' value from a dropdown list that shows all the available tables in the DB. I do not necessarily want to retrieve the table values from DB. I am OK with defining a list with the available tables and the dropdown menu can pull the table names from that list.
So far I only found IS_IN_DB to automatically create a dropdown and PluginDropdown() but that does not serve my purpose. If soemebody can direct me to the proper way of handling this task I'd be really thankful.
Regards.
Update:
After Anthony's suggession I tried the following with , as I'm not that familiar with JS.
{{extend 'layout.html'}}
{{select='NONE'}}
<form>
<select>
{{for item in TOOLS:}}
<option value="{{select=item}}">{{=item}}</option>{{pass}}
</select>
<input type="submit" value="Go!"/>
</form>
<h2>Input form</h2>
{{=form}}
<h2>{{=select}}</h2>
As you might see this doesn't work properly. What I tried to do is to get the user chose value to 'select' variable. But it doesn't work. It always gets the last element in ITEMS (this list is defined in db.py). My next option would be to be call another controller function, passing the user selected value as an argument. Then it can prepare the form with the passed value and send to a view to display
<h2>Input form</h2>
{{=form}}
But I'm not sure how I can assign the user chosen value to an argument and then call another controller function with that arugument value.
If you have any suggestion how I can modify this to get the user chosen value thats very much appreciated. Thank you.

You could create a <select> element listing all the tables, and then load the form associated with the selected table as a web2py component via Ajax. In the view of the main page (e.g., /views/default/index.html):
<script>
jQuery(function() {
jQuery('#table').change(function() {
web2py_component("{{=URL('default', 'form.load')}}" + "/" +
jQuery(this).val(), target='form')
})
})
</script>
{{=SELECT('Select a table', *db.tables, _id='table')}}
<div id="form"></div>
And in a controller (e.g., default.py):
def form():
if request.args(0) in db.tables:
response.generic_patterns = ['load']
return dict(form=SQLFORM(db[request.args(0)]).process())
else:
raise HTTP(404)
Note, db.tables is a list of all the tables defined on the db connection object -- it is used in the SELECT() helper in the view to generate a <select> list of all the tables. The script in the view registers a jQuery event handler that fires whenever a different table is selected from the dropdown. The handler calls the web2py_component() function (which is in /static/js/web2py.js), which loads the form component via Ajax into the div with id="form". It appends the value of the selected table to the URL.
In the controller, the form() function checks for the db table name in request.args(0). It then sets response.generic_patterns so the "generic.load" view will be allowed (by default, generic views are only enabled for local requests). Alternatively, you could define your own "form.load" view, or even use a different extension (e.g., "form.html").
Because the form is loaded as a web2py Ajax component, the form submission will be trapped and submitted via Ajax as well, so it will not result in a full page reload.

Related

AngularJS - memorizing chosen values in form after returing from some special state (view)

I build some form analogously to:
http://tutorials.jenkov.com/angularjs/forms.html
It means that I also use ng-model as chosen value. These values are retrieved from database - there are multiselect options.
<form>
<input type="text" name="firstName" ng-model="myCtrl.firstName"> First name <br/>
<input type="text" name="lastName" ng-model="myForm.lastName"> Last name <br/>
</form>
Controller {
constructor() {
this.firstName = getFirstNameFromDatabase();
}
}
It is sketch of my code - I wouldn't like to show it here.
It is working ok - values are retrieved from database and displayed as proposition in form.
My issue is following:
Let's assume that someone type in this form "abc". Then, someone click button next (it direct to another state, user is directed to another view - lets denote it X).
User can return from X view with back button. I would like to display "abc" (so my app should memorize chosen values).
However, if user type value "abc" and return to menu (or another else state (view) - different from next button) - in this case value shouldn't be memorized.
Can you give me some clues ?
Since you're actually switching pages in your application, you're going to have to put their content in some sort of persistent storage. A couple ideas pop into my head.
Temporary Browser Storage / Cookies
Server-side storage in a Database or Cache
Either way, you'll need to store the data whenever the user manipules the values. And when they switch pages, choose whether to clear the data or not based on whether it's your special view.
Or another idea is to use an angular function to change the url (rather than a simple anchor). Then in that function you can persist the data before switching to your view. But if they go to a different page, it won't get saved. This only works if they navigate based on your page's links.
Usually this sort of thing is accomplished using a single page which includes both your original view and the next view. You can swap out the content using JS so the user doesn't know the difference. So that's still an option too.

ng-include a view with a Controller and with a variable from another Controller

Setting:
I have an angular app
I have a table of geographies. And it shows a names and descriptions.
What I Want:
I want a small view of geography's details to display if the user clicks on a given geography in the table. This view will contain many more bits of information. It will be controlled by a different controller than the table.
main.html:
<div ng-if="displaySingle" ng-controller="GeographyController">
<div ng-include="'html/geography-detail.html'" ng-controller="GeographyDetailController"></div>
</div>
<tr ng-repeat="geography in geographies" ng-controller="GeographyController">
<td ng-click="displaySingleFunction(geography.id)">{{geography.name}}</td>
<td>{{geography.description}}</td>
</tr>
The issue here is that when the user clicks on a given row, I need to pass the id from the that row to the GeographyDetailController. But the controller for that row is in the GeographyController.
Question:
How do I make this line of code:
<div ng-include="'html/geography-detail.html'" ng-controller="GeographyDetailController"></div>
pass a single ID to the GeographyDetailController?
What I Have:
Clicking a given row can make my detail view appear and disappear, it just cannot send that view and its controller the ID that I need it to.
UPDATE 1
This works if I want to follow a link to the page, but I don't, I want to include this view into a larger view.
ui-sref="geographyDetail({uuid:geography.uuid})"
From that I see, GeographyDetailController is a child controller of GeographyController . Then there are several ways to pass the parameter.
You can use the $scope or $rootScope event. That is, when user click on the row, you emit event ($scope.$emit or $rootScope.$emit) from GeographyController , pass your id and call $scope.$on or $rootScope.$on in GeographyDetailController to get the id.
Or you can do like this: when user click on the row, you add a new field in the $scope ($scope.myParam = id) inside the GeographyController and get it like this in the GeographyDetailController ($scope.$parent.myParam).
Personally, I advise you to use the second method.

Having a default value in ng-options in angularjs but also having persistence when we get back to the form again

My current scenario is i query a service and bring an array of values and display it in dropdown in AngularJS using ng-options. The problem is i need a default value at the top of the dropdown somthing like "Select from the list".
I have done that using
<option value="">Select from the options</option>
the problem is i also need to persist the data when i select suppose first value in the dropdown and go to some other page for sometime and come back to the same page which has that dropdown. That time i again need to see the first item selected and not the "Select from the options" thing.
How can i add this text "Select from the options" to the array which comes after querying a service and populates the dropdown also maintaining the persistence using ngModel.
Thanks,
MK
Assuming that the "other page" is still in the same (single-page) Angular application, you can store the selection in a factory and when you come back to the page, initialize the ngModel object (in the controller) by reading it from the factory. There are many ways, but this is one of the usual basic patterns in Angular.
If the visit to the "other page" causes Angular to be reloaded, one typical approach is to store the settings in local storage.

Update binding after server response / How do I selectively update bindings?

I'm trying to prevent the value of a model from updating in a form.
For example :
I have a payment details form that lists the user's saved information (name, address etc) along with the form that is used to edit the same information.
I've been experimenting using the :: for one time binding as I don't want the displayed information to changed when input controls are changed (but I obviously want the models updated values so i can send them to the server for processing).
How do I update the displayed model values after the server responds that the changes have been saved, are ok etc? I can't seem to find a way to update the one time binding (as I'm guessing this is fully the intended functionality).
So I guess my question boils down to :
How do I selectively update bindings on some controls but not others?
Actually you just want to display different vars.
You should try with a temporary model object (that is a copy of your object like "editedObject") and when you validate you will update the original object.
See it working in this plunker
The editing space :
<input ng-model="editCopy.value"> <button ng-click="validateChange()">Change</button>
The ng-repeat :
<td ng-repeat="item in items" ng-click="editItem(item)">
{{item.value}}
</td>
The functions :
$scope.editItem = function(item){
$scope.editCopy = angular.copy(item);
$scope.editingItem = item;
}
$scope.validateChange = function(){
$http.get('index.html').success(function(){
$scope.editingItem.value = $scope.editCopy.value;
});
}

Initializing ngModel with data - AngularJS Bootstrap bs-select

I am maintaining a site that allows users to create a profile of sorts that will allow them to broadcast activities to a feed. I implement ng-grid to keep track of all the profiles that are created, and have created two buttons that allow users to create/edit these profiles. My only problem right now is, when users select a row on the grid and attempt to edit that specific row, the drop-down menu is not auto-populated with the data from ngModel.
This is the part of the form I am having trouble with:
<select ng-model="source.canSendTo" ng-options="value.name for value in sourceCanSendTo" data-style="btn" bs-select></select>
And within the controller, I have sourceCanSendTo defined as:
$scope.sourceCanSendTo = [ {"id":"abc", "name": "ABC"}, {"id":bcd", "name": "BCD"} ... ];
On row selection, I simply set source = the selected item, and console.logs show that all the data is there. The other parts of the form are being populated properly (mainly s), and console.log($scope.source.canSendTo) shows that the original data is there, it's just that select is defaulted to being blank...how would I go about trying to pre-select certain elements on the drop-down select I currently have?
For example, if the profile has 'abc', 'bcd' selected, how can I make it so that when I edit that profile, the drop down box shows 'abc,bcd' instead of just "Nothing Selected"?
Edit: I previously responded to a comment inquiring about bs-select, saying that it simply controlled some CSS elements of the drop down box - seems like this is completely incorrect after a quick google search when everything else led to dead ends. Does anyone have any idea how to properly initialize the model with data so that when I preload my form, the 'can send to' drop down select actually has the selected options selected, as opposed to saying "Nothing Selected"? Thanks in advance for all help!
As you are binding source.canSendTo to the name (value.name) of sourceCanSendTo then you just need to initially have an structure binding the names which had been saved, something like this:
source.canSendTo = ['abc', 'bcd']; //And all the selected values
So you need to construct your source.canSendTo property to this structure.
PS: If you show how you bring your data from the server, I can help you to construct the source.canSendTo property.
$scope.canSendTo must be initialized with a reference to the selected option.
var initialSelection = 0;
$scope.source = { canSendTo : [ {"id":"abc", "name": "ABC"}, {"id":bcd", "name": "BCD"} ... ] };
$scope.canSendTo = $scope.source.canSendTo[initialSelection];
Finally found out what was wrong with my code - seems like the data being stored in the model wasn't the same as what was in ngOptions, played around a bit with ngOptions and managed to get something that works. Working snippet of code:
<select ng-model="sendTo.name" ng-option="value.name as value.name for value in sourceCanSendTo" data-style="btn" multiple bs-select>
(Realized that the variable being used for ngModel was a fairly ambiguous in terms of naming convention, changed it)

Resources