react-final-form handle when field change after change in another field and why formspy runs 2 times? - react-final-form

I'm working with react-final-form and I want to handle two events:
when one field (i.e. "age") was changed because another field (i.e. "date of birth") was changed and age was in validateFields
<Field
name='birthdate'
...
validateFields={['age']}
/>
I'm trying to handle when form was not submitted successfully
<form>
<Field
name='birthdate'
...
validateFields={['age']}
/>
<FormSpy
onChange={(props) => {
console.log('props.submitFailed triggers 2 times', props.submitFailed);
}}
/>
</form>
My formspy onchange runs 2 times. Why this happens?

1/ Answer on first question is that "age" changes not because it listed in validateFields, but because it listed in special function of decorator final-form-calculate, which has function, where I can handle it's change.
2/ Probably it happens because I didn't listed subscription option in subscription of formspy and it runs each subscription option (in my case 2 or 3 of them)

Related

angular 2 Retrieving values from check boxes

I have two check boxes and they are populating when the user is selected, but I now need to check the values and return them before saving them back to database in case they have been changed, below is my plunker with my working code if you select a tradesman from the drop down the ticket boxes are populated.
If someone could advise how I can get check the tick box values that would be great, this is what I have tried but I am missing something:
<input type="input" name="adminis" id="adminis" class="form-control" [(ngModel)]="tradesman.user_roles"/>
Plunker demo
To find whether a checkbox value is changed or not, you can use (change) attribute.
<input type="checkbox" [checked]="tradesman?.user_roles?.includes('Administrator') ? true : false" value="Administrator" (change)="valueChanged($event)"/>Admin
<input type="checkbox" [checked]="tradesman?.user_roles?.includes('General User') ? true : false" value="General User" (change)="valueChanged($event)" />General
In your component, you can manage the data using the event passed.
valueChanged(e:any){
/* e.target.name - for getting the changed field name */
/* e.target.checked - for getting the value - true(checked)/false(unchecked) */
}
Then you can update your array or whatever with this new value.

New to React: Why is one array treated differently than the other?

I'm working on a React app that is fed data from a Rails api. I'm currently working on a form that includes a nested association (i.e. in the model_a has many model_b's and you can create them in the same form).
The problem I'm having is that Rails expects nested association with a certain naming convention and the same field that controls how the parameter is named when its sent to rails also controls how React finds the right data when the Rails API responds.
This becomes problematic on the edit page because I want to show the models_a's (Retailers) already existing model_b's (SpendingThresholds in this case) and when I change the 'name' field to suit the rails side, React doesn't know where to look for that data anymore. When I try to pass the data directly it comes in as a different type of array and certain functions fail.
I think its easier to show than tell here so
initially I had this
<FieldArray
name="spending_thresholds"
component={renderSpendingThresholds}
/>
and data was coming through like
Object {_isFieldArray: true, forEach: function, get: function, getAll: function, insert: function…
to my React app from the Rails API, which worked, however that 'name' isn't to Rails liking (Rails wants it to be called 'spending_thresholds_attributes' for accepts_nested_attributes to work) so I changed it to
<FieldArray
name="spending_thresholds_attributes"
fields={this.props.retailer.spending_thresholds}
component={renderSpendingThresholds}
/>
and data start coming through to the renderSpendingThresholds component in this format
[Object]
0:Object
length:1
__proto__:Array(0)
which React doesn't like for some reason.
Anyone know how to fix this/why those two objects, which hold the same information from the Rails side anyway, are being treated differently?
EDITS
renderSpendingThresholds component
The fields attribute in the renderSpendingThresholds component is the object that's coming through differently depending on how I input it
const renderSpendingThresholds = ({ fields }) => (
<ul className="spending-thresholds">
<li>
<Button size="sm" color="secondary" onClick={(e) => {
fields.push({});
e.preventDefault();
}
}>
Add Spending Threshold
</Button>
</li>
{fields.map((spending_threshold, index) => (
<li key={index}>
<h4>Spending Threshold #{index + 1}</h4>
<Button
size="sm"
color="danger"
title="Remove Spending Threshold"
onClick={() => fields.remove(index)}
>
Remove
</Button>
<Field
name={`${spending_threshold}.spend_amount`}
type="number"
component={renderField}
label="Spend Amount"
placeholder="0"
/>
<Field
name={`${spending_threshold}.bonus_credits`}
type="number"
component={renderField}
label="Bonus Credits"
placeholder="0"
/>
</li>
))}
</ul>
);
It looks like you are passing fields through props and then destructuring the fields out of the props in the callback of the renderSpendingThresholds and discarding the rest. According to the docs, a specific redux-form object is passed through to the render callback. You're essentially overwriting this. Try changing {field} to something like member or spending_threshold. Then you can use the specific map function to iterate over the spending_threshold items. Your field prop should still be available under member.fields or something similar.
For the code that you currently show, who exactly handles the submission?
you use the original flow of form submit?
if so, so please handle that by yourself.
** this line of code, looks weird:
onClick={() => fields.remove(index)}
as you interact directly with the state values...
you need to update the state through
this.setState({fields: FIELDS_WITHOUT_ITEM})
and now when you need to handle your own submission, you don't really care of the input names. Because you are using the state as input.
ie:
class FormSpending extends Component {
handleSubmit() {
var fieldsData = this.state.fields.map(field => {
return {
whateverkey: field.dontcare,
otherKey: field.anotherDontCare
};
});
var formData = {
fields: fieldsData
};
ajaxLibrary.post(URL_HERE, formData).....
}
render() {
return (
...
<form onSubmit={()=>this.handleSubmit()}>
...
</form>
...
);
}
}

valuechangelistener getting called multiple time

I'm working on icefaces upgrade from 1.8 to 3.3 as well as jsf from 1.2 to 2.0.
I have used this link as reference for icefaces upgrade
I'm using ice:datatable in which I have column of checkbox which is grouped for single worker.Check picture which is of before upgrade.
ISSUE 1:
Now Problem faced after migration is that the valuechangelistener of ice:selectbooleancheckbox works fine when I check then uncheck the checkbox of a single worker. But when I do following steps:
Check first worker (This updates the Assigned door column ).
Then check other worker . This unchecks the previous checked worker and also unchecks currently checked worker.
To analyse if there is any issue in phase I used balus C blog to check phase of icefaces when it hits valuechangelistner . Then I found on my second check 2 or more valuechangelistner are called one for previous worker other for current worker(Sometimes twice) this all happens in same invoke application phase.
ISSUE 2:
ValueChangeListener gets called even after Clicking "OK" button or "CANCEL".
Fixed it by adding f:param in ice:commandButton and checking for the param in valuechangelistener method.
Tried:
To change all ice tags in the page to ace tags(Related to datatable i.e datable ,row and column).
Result : Same issue with ace valuechangelistener as well as distorted style. Maybe because I could not find ice:rowHeader equivalent in ace tags and also much more.
Changed only checkbox column to ace:column. Valuechangelistener worked fine but issue with "groupOn" attribute so changed it to "groupBy" and condition="group" still may be it did not work because I used ice:datatable which doesn't support it.
Then I tried to implement groupOn functionality manually. Using rowspan and rendering single checkbox for single worker . But rowspan didn't work. Also when I tried to render checkbox, its style is not exactly same as I need. Check this hattp://postimg.org/image/ih2mgoh7d/ remove 'a' from 'hattp'.
<ace:column groupBy ="#{item.workerName} + #{item.workerId}" rowspan="2"
styleClass= "alignSBChbx" >
<ice:setEventPhase events="ValueChangeEvent"
phase="INVOKE_APPLICATION">
<ice:selectBooleanCheckbox id="dwaCheckbox" value="#{item.select}"
style=" width:'#{appViewSettings.checkboxSize}';
height:'#{appViewSettings.checkboxSize}';"
valueChangeListener="#{dockWorkerAssignmentBean.doorAssignmentChange}"
partialSubmit="true" immediate="true"
disabled="#{!empty dockWorkerAssignmentBean.errorMap['dockWorkersAssignmentPopup:assignmentErrorField']}"
rendered="#{item.visible}">
<f:attribute name="workerIdSelected" value="#{item.workerId}" />
<f:attribute name="assignmentIdSelected" value="#{item.assignmentId}" />
</ice:selectBooleanCheckbox>
</ice:setEventPhase>
</ace:column>
backend
public final void doorAssignmentChange(final ValueChangeEvent event) {
System.out.println("inside door Assignment...");
final String workerIdSelected = (String) event.getComponent().getAttributes().get(
"workerIdSelected");
// unrelevant code
}
}

How to reset input value if a condition fails Primefaces3.5

I have a problem. I am trying to save a information into the database, and before that I check some conditions like if-else like:
if(condition){
//Some Action
}else{
getFacesContext().addMessage(null,MessageFactory.getMessage(ResourceBundle.FACES_BUNDLE.getName(), FacesBundle.LANDLINE_NUMBER_SHOULD_BE_TEN.getName()));
getExternalContext().getFlash().setKeepMessages(true);
return;
}
and When the condition does not match I would like to restore the previous values of the input field.
In that case, it was 22 in place of ss. but the field does not take input except numbers. So the validation fails and shows an message Invalid Input via growl.
How can I also reset the value of the field ss to 22 in java?
Please suggest!
You can use default validator that comes with JSF
<p:inputText id="number" value="" label="Number">
<f:validateDoubleRange minimum="0" maximum="99" />
</p:inputText>
<p:message for="number" />
But if you reset the filed with old value, user may not know what he's entered. However you will not submit until validation success.
Since the input text component implements EditableValueHolder you can call EditableValueHolder.resetValue() on the input component (or call the more convenient RequestContext.getCurrentInstance().reset(inputTextId)) and then re-render it by calling RequestContext.getCurrentInstance().update(inputTextId) if it isn't already being re-rendered through the update attribute of p:ajax.

Grails: checkbox not being set back to false

I am developing a Grails (1.0.4) app where I want to edit a collection of collections on a single page in a grid view. I got it to work quite well depending only on the indexed parameter handling of Spring MVC, except for one thing:
boolean (or, for that matter, Boolean) values in the grid can be set via checkbox, but not unset, i.e. when I check the checkbox and update, the value is set to true, but afterwards when I edit again, uncheck the checkbox and update, it remains true.
This is the GSP code of the checkbox:
<g:checkBox name="tage[${indexTag}].zuweisungen[${indexMitarb}].fixiert" value="${z.fixiert}" />
And this is the HTML that is generated:
<input type="hidden" name="tage[0].zuweisungen[0]._fixiert" />
<input type="checkbox" name="tage[0].zuweisungen[0].fixiert" checked="checked" id="tage[0].zuweisungen[0].fixiert" />
I've found a Grails bug that describes exactly this effect, but it's marked as fixed in 1.0.2, and the problem mechanism described there (underscore in hidden field name is put in the wrong place) is not present in my case.
Any ideas what could be the reason?
This is the solution a guy named Julius Huang proposed on the grails-user mailing list. It's reusable but relies on JavaScript to populate a hidden field with the "false" response for an unchecked checkbox that HTML unfortunately does not send.
I hack GSP to send "false" when
uncheck the box (true -> false) with
custom TagLib.
By default checkBox send nothing when
uncheck, so I use the checkBox as
event handler but send hidden field
instead.
"params" in Controller can handle
"false" -> "true" without any
modification. eg. Everything remain
same in Controller.
The Custom Tag Usage in GSP (sample usedfunc_F is "true"),
<jh:checkBox name="surveyList[${i}].usedfunc_F" value="${survey.usedfunc_F}"></jh:checkBox>
Here is what the Tag generate,
<input type="hidden" name="surveyList[#{i}].usedfunc_F" id="surveyList[#{i}].usedfunc_F" value="false" />
<input type="checkbox" onclick="jhtoggle('surveyList[#{i}].usedfunc_F')" checked="checked" />
The Javascript
<script type="text/javascript">
function jhtoggle(obj) {
var jht = document.getElementById(obj);
jht.value = (jht.value !='true' ? 'true' : 'false');
}
</script>
This is my own solution, basically a workaround that manually does what the grails data binding should be doing (but doesn't):
Map<String,String> checkboxes = params.findAll{def i = it.key.endsWith("._fixiert")} // all checkboxes
checkboxes.each{
String key = it.key.substring(0, it.key.indexOf("._fixiert"))
int tagIdx = Integer.parseInt(key.substring(key.indexOf('[')+1, key.indexOf(']')))
int zuwIdx = Integer.parseInt(key.substring(key.lastIndexOf('[')+1, key.lastIndexOf(']')))
if(params.get(key+".fixiert"))
{
dienstplanInstance.tage[tagIdx].zuweisungen[zuwIdx].fixiert = true
}
else
{
dienstplanInstance.tage[tagIdx].zuweisungen[zuwIdx].fixiert = false
}
}
Works, requires no change in grails itself, but isn't reusable (probably could be made so with some extra work).
I think that the simplest workaround would be to attach a debugger and see why Grails is failing to populate the value. Considering Grails is open source you'll be able to access the source code and once you figure out the solution for it you can patch your version.
I have also found this other bug GRAILS-2861 which mentions the issue related to binding to booleans (see Marc's comment in the thread). I guess that is exactly the problem you are describing.
I would create a small sample app that demonstrates the problem and attach it to the Grails bug (or create a new one). Someone here may be able to debug your sample app or you'll have shown the bug isn't really fixed.
Try this out, set the logs to DEBUG, frist try the first 3 if they don't show the problem up, flip them all to DEBUG:
codehaus.groovy.grails.web.servlet="error" // controllers
codehaus.groovy.grails.web.pages="error" // GSP
codehaus.groovy.grails.web.sitemesh="error" // layouts
codehaus.groovy.grails."web.mapping.filter"="error" // URL mapping
codehaus.groovy.grails."web.mapping"="error" // URL mapping
codehaus.groovy.grails.commons="info" // core / classloading
codehaus.groovy.grails.plugins="error" // plugins
codehaus.groovy.grails.orm.hibernate="error" // hibernate integration
This should allow you to see exactly when and how the parameters setting is failing and probably figure out a work around.

Resources