Dynamic form Issue in Angular - forms

Scenario :
A form is generated dynamically, I used this tutorial to create the form dynamically. When I click "Submit" button, the form value I get in the component is
ts :
doSubmitICR(form) {
console.log(form.value);
}
form.value has the following values
{
CaptainPoint:"0",
Category:"restaurant",
Description:"Test",
DisplayDept:"kitchen",
Group:"restaurant",
GuestPoint:"0",
ItemCode:"1",
ItemName:"Test Item",
PrintingDept:"frontoffice",
SalesRate:"3",
SubGroup:"restaurant",
TAX1:true,
TAX2:true,
TabDisplay:"restaurant",
Unit:"restaurant"
}
TAX1 and TAX2 are dynamic, those form controls were created from a tax table, If the table has TAX3 and TAX4, then instead of TAX1 and TAX2 in the above form, TAX3 and TAX4 form control is generated.
Issue :
If the TAXs are dynamic, how can I pass these values to Web service say WebAPI2 as a model?
Is it possible to filter only the TAX element from the form.value?
Any advice would be appreciated. Thank you.

The solution from alexKhymenko should work well. Alternatively, if the values you want to submit to the API will always have the format of TAX{d}, where d is some combination of digits, you could use the following to get just those values on a request object:
let request = {};
Object.keys(form.value).forEach(key => {
if(/^TAX[\d]+$/.test(key))
request[key] = form.value[key]
});

Related

Dynamic Column configuration in ag-grid

I am trying to load table data dynamically in ag-grid. All column will be listed in sidebar(ToolPanel) check boxes and if user click on any unchecked box then a request will be sent to server and get data for that column and merge into the grid.
I am not sure this can be done with the ag-grid sideBar.
I am thinking of capturing the click event in sideBar but can not found any relevant document.
Please let me know if there is any solution for this.
If you are expecting any event from ag-grid, I think columnVisible might help you.
Have a look at this live example: https://plnkr.co/edit/KpFQp84rZvJgY2gjKRar?p=preview
Uncheck any column and then check.
<AgGridReact
...
onColumnVisible={this.onColumnVisible}
/>
onColumnVisible = params => {
console.log(params);
if (params.visible) {
const colId = params.column.colId;
alert(colId);
// you could identify here, which column was checked
// load data from server for that column
// make sure you also retrieve ID and then associate the column data with appropriate row, i.e.
this.yourHttpSvc.getColData(colId).subscribe(response => {
// iterate through response & rowData appropriately
this.stats.rowData[key][colId] = response[key][colId];
})
}
}
Hope this helps!

xPages REST Service Results into Combobox or Typeahead Text Field

I've read all the documentation I can find and watched all the videos I can find and don't understand how to do this. I have set up an xPages REST Service and it works well. Now I want to place the results of the service into either a combobox or typeahead text field. Ideally I would like to know how to do it for both types of fields.
I have an application which has a view containing a list of countries, another view containing a list of states, and another containing a list of cities. I would like the first field to only display the countries field from the list of data it returns in the XPages REST Service. Then, depending upon which country was selected, I would like the states for that country to be listed in another field for selection, etc.
I can see code for calling the REST Service results from a button, or from a dojo grid, but I cannot find how to call it to populate either of the types of fields identified above.
Where would I call the Service for the field? I had thought it would go in the Data area, but perhaps I've just not found the right syntax to use.
November 6, 2017:
I have been following your suggestion, but am still lost as can be. Here's what I currently have in my code:
x$( "#{id:ApplCountry}" ).select2({
placeholder: "select a country",
minimumInputLength: 2,
allowClear : true,
multiple: false,
ajax: {
dataType: 'text/plain',
url: "./Application.xsp/gridData",
quietMillis: 250,
data: function (params) {
return {
search:'[name=]*'+params.term+'*',
page: params.page
};
},
processResults: function (data, page) {
var data = $.map(data, function (obj) {
obj.id = obj.id || obj["#entityid"];
obj.text = obj.text || obj.name;
return obj;
});
},
return {results: data};
}
}
});
I'm using the dataType of 'text/plain' because that was what I understood I should use when gathering data from a domino application. I have tried changing this to json but it makes no difference.
I'm using processResults because I understand this is what should be used in version 4 of select2.
I don't understand the whole use of the hidden field, so I've stayed away from that.
No matter what I do, although my REST service works if I put it directly in the url, I cannot get any data to display in the field. All I want to display in the field is the country code of the document, which is in the field named "name" (not my choice, it's how it came before I imported the data from MySQL.
I have read documentation and watched videos, but still don't really understand how everything fits together. That was my problem with the REST service. If you use it in Dojo, you just put the name of the service in a field on the Dojo element and it's done, so I don't understand why all the additional coding for another type of domino element. Shouldn't it work the same way?
I should point out that at some points it does display the default message, so it does find the field. Just doesn't display the country selections.
I think the issue may be that you are not returning SelectItems to your select2, and that is what it is expecting. When I do something like you are trying, I actually use a bean to generate the selection choices. You may want to try that or I'm putting in the working part of my bean below.
The Utils.getItemValueAsString is a method I use to return either the string value of a field, or if it is not on the document/empty/null an empty string. I took out an if that doesn't relate to this, so there my be a mismatch, but I hope not.
You might be able to jump directly to populating the arrayList, but as I recall I needed to leverage the LinkedHashMap for something.
You should be able to do the same using SSJS, but since that renders to Java before executing, I find this more efficient.
For label/value pairs:
LinkedHashMap lhmap = new LinkedHashMap();
Document doc = null;
Document tmpDoc = null;
allObjects.addElement(doc);
if (dc.getCount() > 0) {
doc = dc.getFirstDocument();
while (doc != null) {
lhmap.put(Utils.getItemValueAsString(doc, LabelField, true), Utils.getItemValueAsString(doc, ValueField, true));
}
tmpDoc = dc.getNextDocument(doc);
doc.recycle();
doc = tmpDoc;
}
}
List<SelectItem> options = new ArrayList<SelectItem>();
Set set = lhmap.entrySet();
Iterator hsItr = set.iterator();
while (hsItr.hasNext()) {
Map.Entry me = (Map.Entry) hsItr.next();
// System.out.println("after: " + hStr);
SelectItem option = new SelectItem();
option.setLabel(me.getKey() + "");
option.setValue(me.getValue() + "");
options.add(option);
}
System.out.println("About to return from generating");
return options;
}
I ended up using straight up SSJS. Worked like a charm - very simple.

Angular 2 - Removing a Validator error

I wrote a function to update Validator rules on an input if a certain option was selected, using this method (the forms are built using FormGroup):
onValueChanged(data : any) {
let appVIP1 = this.vip1TabForm.get('option1');
let appVIP2 = this.vip2TabForm.get('option2');
let appVIP3 = this.vip3TabForm.get('option3');
//Set required validation if data is 'option3'
if(data != 'option3') {
//Due to initialization errors in UI, need to start with the case
//That there are validations, check to remove them
appVIP1.setValidators([]);
appVIP2.setValidators([]);
appVIP3.setValidators([]);
}
else {
appVIP1.setValidators([Validators.required]);
appVIP2.setValidators([Validators.required]);
appVIP3.setValidators([Validators.required]);
}
}
And I bind that function call to a click event on radio buttons (I initially used the guide from this answer, but the onChange function didn't bind correctly).
This works great, and if the user selects option 1 or 2, the validations are empty, and won't be triggered. If they select option 3, the validations are shown and submission is stopped. However, I run into the problem where the user submits, sees the error, and goes back to change to option 1 or 2. While the validator is cleared, my form still reads as invalid. I have multiple input fields I am validating, so I can't just set the form to valid if the validator is removed this way. How would I go about doing this? Can I remove the has-error for one particular field in the formgroup?
If the correct validators are in place, you can manually call AbstractControl#updateValueAndValidity after they select an option:
this.formBuilder.updateValueAndValidity();
(Where, of course, this.formBuilder is your FormBuilder instance.)
You can also call it on FormElements directly.
This is commonly used to trigger validation after a form element's value has been programmatically changed.
Instead of removing and adding validations. It is more simple to enable and disable fields. You need to add the Validators.required for all required fields. And disable the fields which are not required.
onValueChanged(data : any) {
let appVIP1 = this.vip1TabForm.get('option1');
let appVIP2 = this.vip2TabForm.get('option2');
let appVIP3 = this.vip3TabForm.get('option3');
if(data != 'option3') {
appVIP1.disable();
appVIP2.disable();
appVIP3.disable();
}
else {
appVIP1.enable();
appVIP2.enable();
appVIP3.enable();
}
}

On a HTML Edit form, what is a good approach to have both reset and remember the posted values features?

I have a form which has both server side and client side validation.
It is an edit form, so the original user values are originally pre-populated.
e.g. The original pre-populated values are:
username = yeo
surname = yang
phonenumber = 11-12345
Now, the user edits to the below and submits.
e.g. The edited submitted values are:
username = yeoNew
surname = yangNew
phonenumber = 12-1111
This gets submitted to the serverside and fails the serverside validation because the phonenumber starting with 12 is not allowed.
Anyway, so the form is displayed back to the user as
e.g. The redisplayed form values are:
username = yeoNew
surname = yangNew
phonenumber = 12-1111
This is because my form allows the user to remember their submitted values.
At this stage, I'd like to allow the user to have the ability to reset the form values to the original values using clientside javascript. This is like a reset feature.
e.g. The reset button will restore the form values to:
username = yeo
surname = yang
phonenumber = 11-12345
The reason for this reset feature is that I want the user to have the option to edit the phonenumber again from the original values.
My question is:
What is a good way to keep track of the original values within the HTML so that I can restore it with javascript?
I'm thinking a new attribute called orig='' within the form elements which will store this value.
Is that a good idea?
Any other approaches?
thanks
I would use the HTML5 local storage.
See http://www.w3schools.com/html/html5_webstorage.asp
Using jquery I would do it this way:
<script type="text/javascript">
function load() {
if (localStorage["username"]) {
$('#username').val(localStorage["username"]);
}
if (localStorage["surname"]) {
$('#surname').val(localStorage["surname"]);
}
if (localStorage["phone"]) {
$('#phone').val(localStorage["phone"]);
}
}
function save() {
localStorage["username"] = $('#username ').val();
localStorage["surname"] = $('#surname').val();
localStorage["phone"] = $('#phone').val();
}
</script>

Trying to copy values into multiple embedded forms

I have a Symfony 1.4 application to allow users to enter data to a electrical appliance testing database. The page in questions consists of multiple embedded "new" forms so the user can submit many tests in one go. The form validates and saves correctly, but feedback is that it will be tedious to use.
As much of the data may be the same in each test (e.g. same date, same result, same person doing the testing), I would like the user to be able to fill in values in the top row, then click a button to fill the same information in the rows below. I'm pretty sure this would require javascript, but I don't have much experience.
I would appreciate any suggestions.
Many Thanks.
Well, I managed to figure it out without using javascript.
I put a button on the page
<input type="submit" name="copy_values" value="duplicate">
In the action for the page I included the code...
elseif (isset($_POST['copy_values'])) {
// get values from first embedded test
$newTests = $testList['new_tests'];
$testDate = $newTests[0]['et_date_tested'];
$testedBy = $newTests[0]['et_tester_id'];
$formOptions = array('test_date'=>$testDate, 'tester'=>$testedBy);
$this->form = new MultiTestForm(null, $formOptions);
}
$this->setTemplate('multiAdd');
... which takes the values from the widgets in the top row of the form and creates an array. This is passed as the options array to create a new form.
In the top level form class..
public function configure()
{
...
$subform = new sfForm();
for($i = 0;$i < sfConfig::get('app_new_test_rows'); $i ++)
{
$formToAdd = new TestsForMultiAddForm(null,$this->getOptions());
$subform->embedForm($i, $formToAdd);
}
$this->embedForm('new_tests', $subform);
}
...and in the embedded form class...
public function configure()
{
...
if ($this->getOption('test_date')) {
$this->setDefault('et_date_tested', $this->getOption('test_date'));
}
if ($this->getOption('tester')) {
$this->setDefault('et_tester_id', $this->getOption('tester'));
}
...
}
Not sure if this is the conventional way to approach the problem, but it works!