Django formset equivalent in angular.js - javascript

Django has formsets, where multiple forms can be used in one big form. So let's say one can add in a e.g. library formset mulitple books (providing the author and title) using repetitions of the same book form.
How to achieve the same functionality with Angular.js and Django Rest Framework? I'm new to Angular.js and Django Rest Framework and need some guidance how to be able to dynamically add more forms(e.g. for a book) for a given model in one big form (e.g. my library) and save them in Django Backend.

You can achieve this in 2 steps:
On Frontend
Create a <form> on your page that will structure the data entered by the user as you need. Inside that <form> element, you'll need to use the ngForm for multiple forms' validation to behave correctly (here is a nice explanation of how ngForm works). A hypothetical code snippet would look like:
<form name="libraryForm">
<div ng-repeat="book in vm.newBooksToAdd">
<!-- ngForm directive allows to create forms within the parent form -->
<ng-form name="bookForm">
<div>
<label>Book title</label>
<input ng-model="book.title" type="text" name="title" required>
</div>
<div>
<label>Author</label>
<input ng-model="book.author" type="text" name="author" required>
</div>
</ng-form>
</div>
</form>
In your controller, you can initialize the list of books to add as vm.newBooksToAdd = []; and whenever you want to add a new form to your list of forms for new books, just vm.newBooksToAdd.push({}) an empty object. Thus, you will send to the backend an array of objects representing books you want to create.
On Backend
Now here you'll need to overwrite the .create() method of your view to allow creating many instances at once, because by default it expects a single object. Your view might look like this:
class LibraryViewSet(views.ModelViewSet):
...
def create(self, request):
serializer = self.get_serializer(data=request.data, many=True) # notice the `many` keywork argument here
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return Response(serializer.data, status=status.HTTP_201_CREATED)
Note: If you would like to allow both a single instance creation and creation in bulk, you'll need to adjust your .create() method to check for the data type of request.data.
Note 2: There is a django-rest-framework-bulk library that achieves what you want on the backend, but I didn't try it, so cannot say anything bad or good about it.
Good luck!

Related

angular2 capture info from dynamically generated inputs - possible?

Working on an update form which I would like to generate and capture inputs for a variable sized array
The current unhappy version only supports the first three statically defined elements in the constituency array. So the inputs look like this...
<input #newConstituency1 class="form-control" value={{legislatorToDisplay?.constituency[0]}}>
<input #newConstituency2 class="form-control" value={{legislatorToDisplay?.constituency[1]}}>
<input #newConstituency3 class="form-control" value={{legislatorToDisplay?.constituency[2]}}>
and the function to update pulls the values of the form using the static octothorpe tags.
updateLegislator(newConstituency1.value, newConstituency2.value, newConstituency3.value)
But this doesn't allow for a variable sized Constituency array.
I am able to use *ngFor directive to dynamically create input fields for a theoretically infinitely sized constituency array:
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}}>
</div>
but have not successfully been able to capture that information thereafter. Any kind assistance would be greatly appreciated.
You just have to have a form object in your component that matches the HTML input components that were created.
Template
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}} formControlName="{{constit}}">
</div>
Component
/* create an empty form then loop through values and add control
fb is a FormBuilder object. */
let form = this.fb.group({});
for(let const of legislatorToDisplay.constituency) {
form.addControl(new FormControl(const))
}
Use two-way data binding:
<div *ngFor="constit of legislatorToDisplay?.constituency; let i = index">
<input [(ngModel)]="legislatorToDisplay?.constituency[i]">
</div>

HTML Templating Engines and Liquid

I'm trying to get my head round templating engines and if there is something suitable for my requirements.
I'd like to specify HTML and provide dynamic functionality from within the HTML itself. For example, say I had a check box on a page
<label><input type="checkbox" id="cbox1" value="first_checkbox"> This is my checkbox</label>
I'd like to specify logic within HTML so that I display more content only if that checkbox has been checked, e.g.
// if #cbox1.checked == true
<h1>The check box is checked</h1>
// else
<h1>The check box is not checked</h1>
// end
Now, it is likely that liquid will be used to provide dynamic functionality based on a data store. So it'd also be nice to use the same liquid syntax to make the form dynamic (i.e. use liquid syntax in the if conditional above).
Is it possible to write a 'js engine', perhaps using jquery, that I could include in my web pages that would allow me to use liquid syntax but bind to variables in the 'js engine' as well as the data store to make my content dynamic?
Or, is there a better approach?
I would recommend using Vue.js (https://vuejs.org/).
The template engine is very easy to learn, and provides all the functionality you mention.
Here is a working example of your scenario:
https://jsbin.com/kikaxecogo/edit?html,output
But all you need to do is initialise Vue:
new Vue({
el: '#app',
data: {
showData: false
}
});
and write the template data:
<input type="checkbox" v-model="showData">
<div v-if="showData">
This is visible using v-if
</div>
<div v-else>
The check box is not checked
</div>
I've written a introduction guide to Vue.js here https://steveedson.co.uk/vuejs-intro/
You can also bind to other text inputs, data from ajax sources etc:
<input type="text" v-model="name">
<p>Hello {{ name }}</p>
And everything will update automatically.
As an alternative to Vue.js, there is also:
https://facebook.github.io/react/
https://angularjs.org/

Better way to use a variable in html

I wanted to have a template which would be used to create dynamic user detail forms. But I need to have different ids for all elements, so as to post the details correctly. My template looks like:-
<div id="user-template" class="hidden">
<div class='lbl-div' id='user(user_number)'>
<label>User(user_number)</label>
</div>
<label class="lbl" id="user(user_number)_firstname">Firstname:</label>
<input type="text" value="" />
<label class="lbl" id="user(user_number)_lastname">Lastname:</label>
<input type="text" value="" />
</div>
Here, user_number is a variable. onclick of a button would pick this template-->replace user_number with a global variable-->increment the global variable-->append the modified template as a child to the parent div.
I replace the variables as:-
template = template.replace(/\(user_number\)/g, count);
count++;
Here count is the global variable.
Is there a better way to achieve this(using the template dynamically with changing ids)?
If you are using html templates, then try using any templating engine, like underscore, mustache. But templating engine will not give you two way binding between template and your data. It just render template with given data.
If you want to use pure two way databinding application, then try using web application frameworks like angularjs or emberjs.

Grails and Jasper - Send input fields values from create view as parameters to a report

I'm having problems trying to send input fields values to a Jasper report. I know how to send parameters to a report but I always did this using the show.gsp view because it was quite simple to do something like this:
<g:jasperReport controller="liquidacionDeEstano" action="crearReporte" jasper="liquidacion_estano" format="PDF" name="ReporteLiquidacion${liquidacionDeEstanoInstance.lote}">
<input type="hidden" name="LIQ_SN_ID" value="${liquidacionDeEstanoInstance.id}" />
</g:jasperReport>
Where LIQ_SN_ID is a "static" parameter used by the report.
But now I want to fill some input fields and use this values as parameters. So, what I'm doing is to use some input fields out of the jasperReport tags and hidden fields inside the jasperReport tags. Then I copy the values from the input fields to the hidden fields using JavaScript.
To generate the report I'm just using SQL and the parameters passed are used for filtering.
This is my controller closure to create the report (I think I don't need anything else but the parameters):
def crearReporte = {
chain(controller:'jasper',action:'index',params:params)
}
This is the code in the GSP form to invoke the report:
<g:jasperReport controller="reporteLotesRecepcionados" action="crearReporte" jasper="reporte_recepcion_fechas" format="PDF" name="ReportePorFechas">
<input type="hidden" id="ELEMENTO_1" name="ELEMENTO_1" />
<input type="hidden" id="ELEMENTO_CLASS_1" name="ELEMENTO_CLASS_1" />
<input type="hidden" id="FECHA_INICIAL_1" name="FECHA_INICIAL_1"/>
<input type="hidden" id="FECHA_FINAL_1" name="FECHA_FINAL_1"/>
<input type="hidden" id="ESTADO_LOTE_1" name="ESTADO_LOTE_1"/>
</g:jasperReport>
I checked that all the parameters are correct (hidden fields values) using Firebug and a Web Developer extension for Firefox but when I click the link to the report this error is produced:
Timestamp: 23/12/2013 07:20:00 p.m.
Error: TypeError: link.parentNode._format is undefined
Source File: http://localhost:8080/Liquidaciones/reporteLotesRecepcionados/create
Line: 660
Following the link to the error this automatic generated code is shown:
<script type="text/javascript">
function submit_reporterecepcionfechas(link) {
link.parentNode._format.value = link.title;
link.parentNode.submit();
return false;
}
</script>
I don't know what I'm doing wrong. In fact this is the first time I try to generate a report using values as parameters from input fields.
Please help me with this.
Thank you in advance.
I know this have been here for 11 months withuoth an answer so...
Jasper tags uses their own form and since html forbids to have nested forms:
Content model: Flow content, but with no form element descendants.
(HTML)
Jasper documentation says : "Note that the jasperReport tag should not be nested with a form element, as it uses a form element in its implementation, and nesting of forms is not allowed."
Finally I solved it but I'm not sure how I did it. Ok, here is what I did:
As you know, since Grails 2 (I think) there is a form.gsp used by the create.gsp and edit.gsp views. I was using just the create.gsp (and, in consequence, the form.gsp) view to have the input fields to obtain parameters to generate reports. Initially I located the code:
<g:jasperReport controller="reporteLotesRecepcionados" action="crearReporte" jasper="reporte_recepcion_fechas" format="PDF" name="ReportePorFechas">
<input type="hidden" id="ELEMENTO_1" name="ELEMENTO_1" />
<input type="hidden" id="ELEMENTO_CLASS_1" name="ELEMENTO_CLASS_1" />
<input type="hidden" id="FECHA_INICIAL_1" name="FECHA_INICIAL_1"/>
<input type="hidden" id="FECHA_FINAL_1" name="FECHA_FINAL_1"/>
<input type="hidden" id="ESTADO_LOTE_1" name="ESTADO_LOTE_1"/>
</g:jasperReport>
INSIDE the <g:form></g:form> tags. So, I tried, as an experiment, to copy the code to declare the input fields and the code to generate the report from form.gsp file to create.gsp, OUTSIDE the <g:form></g:form> tags (I'm not using the form.gsp file anymore). And that was all. It's working perfectly now.
As I told you I don't know how this problem has been solved. Maybe it is mandatory to have the tags outside any <g:form></g:form> tags...
...but why?
PD.: I created a domain class to have the form to enter the values that were going to be parameters. All of you must be thinking this was completely unnecessary and that having an ordinary HTML form was enough , well, I'm a Grails newbie, sorry.

Data Binding between pages in Angularjs

I am trying to understand data binding in Angularjs.
What I want to do is establish binding between pages that is if I change the input on first.html, the data should automatically change in second.html.
For example,
This is first.html:
<div ng-controller="MyCtrl">
<input type="text" ng-model="value"/><br>
{{value}}
<input type="submit" value="Second page"/>
</div>
and say second.html has only this piece of code {{value}}.
and in the .js file we have $routeProvider which takes the template url as 'second.html' & the controller is 'MyCtrl'.
So the controller is:
MyApp.controller(function($scope){
$scope.value="somevalue";
})
By doing the above way the {{value}} on the second.html is getting the value "somevalue". Which is comming from the controller.
But if I change the input value dynamically that is on the first.html, the value on the second.html is not getting that value.
My question is how do I bind the value on second.html with first.html automatically.
To understand the question clearly, Suppose there is an input field for entering text and a submit button on first.html, then I want to get the Input value of the text field of the first.html on the second.html page on Submit.
Use a service and store your model there. Gloopy already has a good example of this here: https://stackoverflow.com/a/12009408/215945
Be sure to use an object property instead of a primitive type.
If you'd rather use $rootScope, then as above, define an object, rather than a primitive:
$rootScope.obj = { prop1: "somevalue" }`
then bind to that object property in your views:
<input type="text" ng-model="obj.prop1">
{{obj.prop1}}
If you attach your data to $rootScope if will survive transitions across controllers and be part of all $scopes (prototype inheritance magic)
//**attach in controller1:**
function MyCtrl1($rootScope) {
$rootScope.recs= { rec1 : "think philosophically" };
}
//**do nothing in controller for view2:**
function MyCtrl2($scope) {
//nothing
}
//**Markup for view2: automaticall makes use of data in $routeScope**
<p>Try doing this: {{recs.rec1 }}</p>
//**markup for view1 to respond to OPs question in comments**:
<input ng-model="recs.rec1" />
Update: Creating a custom service is a more scalable and structurally sound way to handle this, but the $rootScope method is the quick and dirty way.
Update2: added view1 markup to respond to OP question, edited example to take advantage of correct advice to use object rather than primitive.
Found the Solution to what I was looking for, The solution is in the Angular docs, here is the link http://docs.angularjs.org/cookbook/deeplinking.
Some part of the example on that link answers my question.
You should user $broadcast, $emit or scope communication. Try to avoid overloading the rootScope. It is as a bad practice as saving data into the application sessions.

Categories

Resources