How to create text fields dynamically - frp

Say I have a record like this:
type Library = { books : [Book] }
type Book = { title : String, year : Int }
And I want to dynamically create a UI to fill the Library record.
I would want a button "Add" which would create two text fields per book.
And editing inside any text field would immediately be synced in the record structure.
How could I achieve this with elm 0.12?

Learn about interactive UI elements and understand the TODO list example, which is pretty much isomorphic with what you want to acquire.

Related

Zoho Creator: Sort sub-form records in both Main Forms and Views/Reports

Zoho Creator is a great system for quickly creating simple cloud applications. I've run into a problem with sub-forms, though: currently, Zoho Creator does not provide functionality for sorting sub-form records by a specified column. Instead, it sorts records in the order in which they were added.
My sub-form is a Creator Form that's linked to another Creator Form (basically, 2 different tables). The forms are linked with a bi-directional lookup relationship.
I've seen and tried implementing these "hacks", but none of them work for my situation:
[Zoho Forums, "Subforms sorting rows"][1]
[Zoho Forums, "Hack to sort rows of a subform and pre-populate row fields that I want to preset"][2]
I also called Zoho tech support, and after looking at my application, they said that sorting sub-form records is not currently possible.
Any other ideas?
My tested solution is still a hack, but until Zoho implements a method to sort sub-form records via the GUI, this will have to do.
First, create a function that you can call from anywhere (e.g. when a new sub-form record is added or changed)--for details on that, go here: http://www.zoho.com/creator/help/script/functions.html
This function will first duplicate the sub-form records by the parent record ID (sorting by the appropriate column) and then delete all sub-form records that were inserted before the script started:
int SubFormRecords_SortByAnything_ReturnCount(int ParentRecordID)
{
scriptStartTime = zoho.currenttime;
for each rSubFormRecord in SubFormRecords [ParentFieldName = input.ParentRecordID] sort by FieldName1, FieldName3, FieldName2
{
NewSubFormRecordID = insert into SubFormRecords
[
FieldName1 = rSubFormRecord.FieldName1
FieldName2 = rSubFormRecord.FieldName2
FieldName3 = rSubFormRecord.FieldName3
];
}
delete from SubFormRecords[ (Series == input.ParentRecordID && Added_Time < scriptStartTime) ];
return SubFormRecords[ParentFieldName == input.EventID].count();
}
Once the above sorting function is in place (customized for your application), call it when appropriate. I call it when adding a record associated with the sub-form, or when I change the sorting column values.
That works well, and as long as you don't have complex logic associated with adding and deleting records, it should have minimal impact on application performance.
Please let me know whether that works for you, and if you have any better ideas.
Caveat: This solution is not suitable for forms containing additional sub-form records because deleting the records will delete linked sub-form values.
Thanks.
I have a a very simple workaround:
1) You have to add a Form Workflow
2)Record Event - Create OR Edit OR Create/Edit (As per your requirement)
3)Form Event - On successful form submission
4)Let Main_Form be the link name of the Main Form
4)Let Sub_Form be the Link name of the Sub Form (Not the link name you specify in the main form for the same sub form)
4)Let Field1 and Field2 are fields of subform on which you want to sort subform records
5)Let Link_ID be lookup field of Mainform ID in the subform
Workflow
1)Sub_Records = Sub_Form[Link_ID == input.ID] sort by Field1,Field2;
(sort by multiple fields, add asc/desc as per requirement)
2)delete from Sub_Form[Link_ID == input.ID];
3)for each sub_record in Sub_Records
{
insert into Sub_Form
[
Added_User = zoho.loginuser
Link_ID = input.ID
Field1 = sub_record.Field1
Field2 = sub_record.Field2
]
}
//Now you check the results in edit view of the main form

how to create a new record in form datasource from x++

In form Journal Voucher (AR>Journal> PaymentJournal> clicking buttonLines). I want to create a new record from x++ code.
I have seen few methods in the form viz create(), initvalue(), ledgerJournalEngine_custPayment... etc which are called when we press ctrl+n . How we could use these methods through x++ code to create a record using standard functionality.
plz help.
Before you elaborated, I thought you were trying to create your own custom form extending the journal functionality. If you're just trying to create a tool, you can just create a new Settlement Using Cust Group button. In the clicked event, call your transaction marking form or whatever you do to get the transactions you want to use. Then put something like this in it:
void clicked()
{
;
element.lock();
super();
// Put your code here to call the open transaction editing code
// CREATE THIS CUSTOM METHOD on C\LedgerJournalEngine_CustPayment\settleTransCustGroup
ledgerJournalEngine.settleTransCustGroup(ledgerJournalTable);
ledgerJournalTrans_ds.active();
ledgerJournalTrans_ds.reread();
ledgerJournalTrans_ds.executeQuery();
//recalculate balances
ledgerJournalEngine.newJournalActive(ledgerJournalTable, true);
element.firstField();
element.unLock();
}
Then in the new method you created, which I named settleTransCustGroup, you can loop over your records in the testLedgerJournalSpecTrans modeling off of something similar to this (custom method created on the engine class):
void settleTransCustGroup(LedgerJournalTable _ledgerJournalTable)
{
LedgerJournalTrans ledgerJournalTrans;
;
// Turn this stuff into a loop and default whatever else you need
ledgerJournalTrans.clear();
ledgerJournalTrans.initValue();
ledgerJournalTrans.AccountNum = '100003';
ledgerJournalTrans.AmountCurCredit = 10;
this.initValue(ledgerJournalTrans);
ledgerJournalTrans.insert();
this.write(ledgerJournalTrans);
ledgerJournalTrans.clear();
ledgerJournalTrans.initValue();
ledgerJournalTrans.AccountNum = '100005';
ledgerJournalTrans.AmountCurCredit = 15;
this.initValue(ledgerJournalTrans);
ledgerJournalTrans.insert();
this.write(ledgerJournalTrans);
}
Generally, your X++ code would look something like this:
static void InsertRecord(Args _args)
{
LedgerJournalTrans ledgerJournalTrans;
;
ledgerJournalTrans.AccountNum = "10000";
ledgerJournalTrans.AmountCurCredit = 50.64;
ledgerJournalTrans.AccountType = LedgerJournalACType::Ledger;
ledgerJournalTrans.insert();
}
You can replace the fields and values as needed. If any fields are missing, the error will display in the infolog (for example, if you were to run the above, you will get a "Currency code must be specified" error), so be sure all required fields are addressed.
In most cases, you can also call ledgerJournalTrans.initValue(); before assigning your values to pre-populate the record with default AX values. I believe this will be the same as what you see when you use Ctrl + N on the form. In the above example, doing so will cause the Currency Code to be filled in, and the record to be saved correctly (at least on our system).
There is no magical way of calling standard funcionality out of the frameworks quoted here on other comments. For each Ledger Type (Accounting, Inventory, Orders, Payments, ...), the way of creating and initializing lines is different and you have to work on this specific way if you want the journal to post properly.
There are a lot of examples on google of X++ code that inserts journal transactions for almost every type of them. It's not easy, but at least it's always almost the same code and it can be easilly reused.

Handling parameters from dynamic form for one-to-many relationships in grails

My main question here is dealing with the pramas map when having a one-to-many relationship managed within one dynamic form, as well as best practices for dealing with one-to-many when editing/updating a domain object through the dynamic form. The inputs for my questions are as follows.
I have managed to hack away a form that allows me to create the domain objects shown below in one Dynamic form, since there is no point in having a separate form for creating phone numbers and then assigning them to a contact, it makes sense to just create everything in one form in my application. I managed to implement something similar to what I have asked in my Previous Question (thanks for the people who helped out)
class Contact{
String firstName
String lastName
// ....
// some other properties
// ...
static hasMany = [phones:Phone]
static mapping = {
phones sort:"index", cascade: "all-delete-orphan"
}
}
class Phone{
int index
String number
String type
Contact contact
static belongsTo = [contact:Contact]
}
I basically managed to get the values from the 'params' map and parse them on my own and create the domain object and association manually. I.e. i did not use the same logic that is used in the default scaffolding, i.e.
Contact c = new Contact(params)
etc...., i just looped through all the params and hand crafted my domain objects and saved them and everything works out fine.
My controller has code blocks that look like this (this is stripped down, just to show a point)
//create the contact by handpicking params values
def cntct = new Contact()
cntct.firstName = params.firstName
cntct.lastName = params.lastName
//etc...
//get array of values for number,type
def numbers = params['phone.number']
def types = params['phone.type']
//loop through one of the arrays and create the phones
numbers.eachWithIndex(){ num, i ->
//create the phone domain object from
def phone = new Phone()
phone.number = num
phone.type = types[i]
phone.index = i
cntct.addToPhones(phone)
}
//save
My questions are as follows:
What is the best practice of handeling such a situation, would using Command objects work in this case, if yes where can i found more info about this, all the examples I have found during my search deal with one-to-one relationships, I couldn't find an example for one-to-many?
What is the best way to deal with the relatiohsips of the phones in this case, in terms of add/removing phones when editing the contact object. I mean the creation logic is simple since I have to always create new phones on save, but when dealing with updating a contact, the user might have removed a phone and/or editing an exiting one and/or added some new phones. Right now what I do is just delete all the phones a contact has and re-create them according to what was posted by the form, but I feel that's not the best way to do it, I also don't think looping over the existing ones and comparing with the posted values and doing a manual diff is the best way to do it either, is there a best practice on how to deal with this?
Thanks, hopefully the questions are clear.
[edit] Just for more information, phone information can be added and deleted dynamically using javascript (jquery) within the form [/edit]
disclaimer: i do not know if the following approach works when using grails. Let me know later.
See better way for dynamic forms. The author says:
To add LineItems I have some js that calculates the new index and adds that to the DOM. When deleting a LineItem i have to renumber all the indexes and it is what i would like to avoid
So what i do
I have a variable which stores the next index
var nextIndex = 0;
When the page is loaded, i perform a JavaScript function which calculates how many child The collection has and configure nextIndex variable. You can use JQuery or YUI, feel free.
Adding a child statically
I create a variable which store the template (Notice {index})
var child = "<div>"
+= "<div>"
+= "<label>Name</label>"
+= "<input type="text" name=\"childList[{index}].name\"/>"
+= "</div>"
+= "</div>"
When the user click on the Add child button, i replace {index} - by using regex - by the value stored in the nextIndex variable and increment by one. Then i add to the DOM
See also Add and Remove HTML elements dynamically with Javascript
Adding a child dinamically
Here you can see The Paolo Bergantino solution
By removing
But i think it is the issue grow up when deleting. No matter how many child you remove, does not touch on the nextIndex variable. See here
/**
* var nextIndex = 3;
*/
<input type="text" name="childList[0].name"/>
<input type="text" name="childList[1].name"/> // It will be removed
<input type="text" name="childList[2].name"/>
Suppose i remove childList1 What i do ??? Should i renumber all the indexes ???
On the server side i use AutoPopulatingList. Because childList1 has been removed, AutoPopulatingList handles it as null. So on the initialization i do
List<Child> childList = new AutoPopulatingList(new ElementFactory() {
public Object createElement(int index) throws ElementInstantiationException {
/**
* remove any null value added
*/
childList.removeAll(Collections.singletonList(null));
return new Child();
}
});
This way, my collection just contains two child (without any null value) and i do not need to renumber all the indexes on the client side
About adding/removing you can see this link where i show a scenario wich can gives you some insight.
See also Grails UI plugin
Thanks,
Your answer brought some insight for me to do a wider search and I actually found a great post that covers all the inputs in my question. This is just a reference for anyone reading this. I will write a blog entry on how I implemented my case soon, but this link should provide a good source of ino with a working exmaple.
http://www.2paths.com/2009/10/01/one-to-many-relationships-in-grails-forms/
Most of the time I use ajax to manage such problem.
So when the user clicks add new phone I get the template UI from the server for manageability purpose ( the UI just same GSP template that I use to edit, update the phone), so this way you are not mixing your UI with your js code, whenever you want to change the UI you have to deal only with our GSP code.
Then after getting the UI I add it to the page using jquery DOM manipulation. Then after filling the form when they hit add(save) the request is sent to the server via ajax and is persisted immediately.
When the user clicks edit phone the same UI template is loaded from the server filled with existing phone data, then clicking update will update the corresponding phone immediately via ajax, and same thing applies to delete operation.
But one day I got an additional scenario for the use case that says, "until I say save contact no phone shall be saved on the backend, also after adding phones to the contact on the ui if navigate away to another page and come back later to the contact page the phones I added before must be still there." ugh..
To do this I started using the Session, so the above operations I explained will act on the phone list object I stored on the session instead of the DB. This is simple perform all the operation on the phonesInSession but finally dont forget to do this(delete update):
phonesToBeDeleted = phonesInDB - phonesInSession
phonesToBeDeleted.each{
contact.removeFromPhones(it)
it.delete()
}
I know I dont have to put a lot of data in session but this is the only solution I got for my scenario.
If someone has got similar problem/solution please leave a comment.
First, in all your input fields names you add an #:
<input type="text" name="references[#].name"/>
Second, add call a function before submitting:
<g:form action="save" onsubmit="replaceAllWildCardsWithConsecutiveNumbers();">
Third, this is the code for the function that you call before submitting the form:
function replaceAllWildCardsWithConsecutiveNumbers(){
var inputs = $('form').find("[name*='#']");
var names = $.map(inputs, function(el) { return el.name });
var uniqueNames = unique(names);
for (index in uniqueNames) {
var uniqueName = uniqueNames[index];
replaceWildCardsWithConsecutiveNumbers("input", uniqueName);
replaceWildCardsWithConsecutiveNumbers("select", uniqueName);
}
}
function unique(array){
return array.filter(function(el, index, arr) {
return index === arr.indexOf(el);
});
}
function replaceWildCardsWithConsecutiveNumbers(inputName, name){
counter = 0;
$(inputName + "[name='" + name + "']").each(function (i, el) {
var curName = $(this).attr('name');
var newName = curName.replace("#", counter);
$(this).attr('name', newName);
counter += 1;
});
}
Basically, what the code for replaceAllWildCardsWithConsecutiveNumbers() does, is to create a list for all input (or select) elements whose name contains an #. Removes the duplicates. And then iterates over them replacing the # with a number.
This works great if you have a table and you are submitting the values to a command object's list when creating a domain class for the first time. If you are updating I guess you'll have to change the value of counter to something higher.
I hope this helps someone else since I was stuck on this issue for a while myself.

Grails: can remoteField update multiple fields?

Assume i have a book entity with an isbn field.
When entered a isbn number, i want 2 fields to be updated: title and author.
My controller looks like this:
def ajaxGetBook = {
def book = Book.findByIsbn(params.isbn)
if(book==null) book = new Book()
render book as JSON
}
So my call works, and i get a full JSON Book.
Now i would like to update 2 texfields by the update attribute
<g:remoteField action="ajaxGetBook" update="title" name="isbn" value="${bookInstance?.book?.isbn}" paramName="isbn"/>
Now the title field gets updated with the full book object, so that doesn't work.
Is it possible to update field title with only the JSON book.title?
Is it possible to update more fields at once?
I could render book.title as JSON but that works for only one field.
Thank you
Well, the g:remoteField tag is explicitly for one field, so you can't use it to update more than one. So, you're left with 2 easy choices:
Use 2 g:remoteField calls... this isn't a bad option, as they would happen in near parallel, as they are Async calls.
Roll your own Ajax. use g:remoteFunction instead, and have the JS function that you place in the "success" attribute take your book, and update the appropriate HTML fields.

best practice Treeview populating from differents kinds of objects

I would like to populate a Treeview.
Here is what I have in DB :
table : Box
BoxID
BoxName
table Book :
BookID
BookName
BoxID (fk Box.BoxID)
table Chapter:
ChapterID
ChapterName
BookID (fk Book.BookID)
As you may know a treeview is made up of treenode object.
A treenode object have a text property and a tag property.
The "text" property is the text that it's display on the screen for this node and the "tag" is an "hidden" value (usually uses to identify a node)
So in my case; the fields ending with ID will be used in the "tag" property and the fields ending with Name will be used in the "text" property
example :
so for a book; I will use the BookID field for the "tag" property and BookName field for the "text" property
note : I use a dbml so I have a Book object, Box object and Chapter object and I use linq to get them from the db.
So my question is; what is the best practice to build this tree?
I have a solution but it's really ugly because it looks like I'm duplicating the code.
The problem is that the values I need to extract for the text and tag properties are identified by differents fields name in the db
So for the book level, I need to get the BookID field to populate the tag property of my node; for the box level, I need to get the BoxID field to populate the tag property , ....
How can I make a kind of generic way to do it ?
I hope I made myself clear enough, don't hesitate to ask me questions :)
Thx in advance
Here is what I have for the moment
I get the list of box with a linq (dbml) request.
List<Box> MyListofBox = getMyListofBox();
Treenode tnBox = null;
Treenode tnBook =null;
foreach(Box b in MyListofBox )
{
tnBox = new TreeNode();
tnBox.tag = b.BoxID;
tnBox.text = b.BoxName;
List<Book> MyListofBook = getMyListofBookByBoxID(b.BoxID)
foreach(Book boo in MyListofBook )
{
tnBook = new TreeNode();
tnBook.tag = boo.BookID;
tnBook.text = boo.BookName;
tnBox.nodes.add(tnBook);
}
mytreeview.nodes.add(tnBox);
}
but of course I don't like this solution...
do you have a better way ?
I would extract the you need from the database in the form of a struct, possibly via the anonnoumous type that has been added to C# together with linq. Then I would populate insert this data into the place in the tree.
From what I get, you are trying to get each property separately, which will not work so well, because then you will have to make a call to the database for each separate property, which is very wasteful.
Addition based on what you have added
I do not believe the code can be more compact - the names you call are similar, but not the same and the way you do it was what I was trying to explain earlier.
You could
Define an key/value interface that both Box and Book implement
Define a delegate that returns a TreeNode and create delegate methods that accept Box and Book
However, I think the code is fine as written. Sometimes you just have to code it and there's little point in further abstracting or optimizing it.
The only issue I see in the code is that you're making a database call in a loop. Whether or not that's a problem depends on the application.

Resources