How to set hidden fields in redux form in react native? - react-native

How to set hidden fields in redux form in react native ?
i jsut cannot find any way on how to do that . any help?

i ended using this :
this.props.dispatch(change("FORM_NAME","FIELD_NAME","VALUE"))
after this code runs, the form will create the field if it does not exists

I have faced the same issue.
What I do is to declare a Field like this and set the height to 0.
It is a little bit hacky but it works in my case.
<Field
component={TextInput}
name="departure_city_name"
type="hidden"
style={{ height: 0 }}
/>
And I change the value like this : this.props.change("departure_city_name", cityData.name);
Hope it helps.

you don't need to dispatch any action just perform this change whenever you need a hidden field in redux form.
this.props.change('Field_name', value)

Technically you don't need to create a type=hidden field because you can call the change function for the 'hidden' field you want to change if the field doesn't exist Redux-form will add it to your form state like an actual field
MyForm = reduxForm({
form: 'myForm'
})(MyForm)
MyForm = connect(
state => ({
initialValues: { areYouOk: 'no' }
})
)(MyForm)
export default MyForm
Whether you've set up initial values or not you'll always be able to call the change function with your new hidden value and it'll work anyway
let MyForm = ({ submitHandler, change }) => {
return (
<form onSubmit={submitHandler}>
<button
onClick={() => {
change('areYouOk', 'yes');
}}
label={'Yes'}
/>
</form>
);
}

Related

Edit field name is different from source field name

I'm working with a form and I need to submit a field that's called "Lang-en" however the field name in the get request is called "Lang".
Now I need to show the value of the field in the submit form using the "Lang" source however when I submit it, I want it to be submitted as "Lang-en".
Anyway to achieve this?
I realize It's not the best api but that's what I'm working with unfortunately.
Use the transform prop:
export const UserCreate = (props) => {
const transform = data => ({
...data,
fullName: `${data.firstName} ${data.lastName}`
});
return (
<Create {...props} transform={transform}>
...
</Create>
);
}
use URIEncode before transfer。。。

Does event, onBlur, work with the React Admin useInput hook on custom field?

I have a custom field that takes JSON and dynamically prints out TextField objects.
For each TextField I have an onChange and onBlur event. The onChange is for updating the state and the onBlur is for updating the final value to be past to the API and saved.
I'm using the useInput hook to save the updated value, however, when I use onBlur it doesn't save the value.
If I only use onChange it DOES save the value, but only the first key stroke, which is why I switched to onBlur. Any ideas? Here's the code:
const DefaultField = props => {
const {
input,
} = useInput(props.record);
let parsedObj = JSON.parse(props.record.values);
const [defaultState, setDefaultState] = React.useState({
websiteLink: parsedObj.websiteLink,
menuInstructionsLink: parsedObj.menuInstructionsLink,
surveyLink: parsedObj.surveyLink
});
const handleBlur = (event) => {
parsedObj[event.target.name] = event.target.value;
props.record.values= JSON.stringify(values);
//event.target.value is the expected value but it's not persisted when I save it.
};
const handleChange = (event) => {
setDefaultState({ ...defaultState, [event.target.name]: event.target.value });
};
return (
<FormControl component="fieldset">
<FormGroup {...input} id="defaultGroup" aria-label="position">
<React.Fragment>
{ Object.keys(parsedObj).map((key) => (
<TextField
id="standard-full-width"
name={key}
label={key}
onBlur={handleBlur}
onChange={handleChange}
style={{ margin: 8, width: '500px' }}
value={defaultState[key]}
fullWidth
margin="normal"
/>
))}
</React.Fragment>
</FormGroup>
</FormControl>
)
}
I never solved it properly, but I did discover that the dataProvider was being called twice. The first time it would send the expected values, but the second time the values were set back to the original, however I noticed that the field "previousData" had the values I needed. For now I'm just making sure to use the "previousData" field. This isn't the prettiest solution, but for now it's working. Maybe it's a bug or something sinister is going on.

Validation form with optional fields react-hook-forms

I'm trying to handle a form composed by two parts, one fixed and the other one that gets displayed by a switch.
To handle the forms I'm using react-hook-form.
I defined a validation scheme in the file validation.ts inside the constants folder.
About the optional part I defined a sub-object but it doesn't work and it gives a compile time error.
Because of this I opted for the solution you'll find in the link at the bottom of the page
Although I defined the optional input fields inside the validation file, they don't get recognized when I press the submit button.
How can I fix this problem?
At this link you can find a working example of the problem.
The main problem is with your components/Form component, it has this line
// components/Form.tsx
return child.props.name
? .... : child;
What you have done here is ignoring all child components without the name prop,
where as when rendering the component what you did was rendered them inside <></>, use below alternative instead.
// in App.tsx
{isEnabled ? <Input name="trailerPlate" placeholder="Targa rimorchio" /> : <></>}
{isEnabled ? <Input name="trailerEnrolment" placeholder="Immatricolazione rimorchio" /> : <></>}
Still the validation won't because you need to register the components and your current useEffect code doesn't account for change in number of input fields.
Use below code instead
React.useEffect(() => {
....
....
}, [
register,
Array.isArray(children) ?
children.filter(child => child.props.name).length : 0
]
);
We are using the count of child components with name prop as a trigger for useEffect.
And finally you also have to unregister the fields when you toggle the switch,
below is a sample code, feel free to change it according to your preference.
const { handleSubmit, register, setValue, errors, unregister, clearErrors } = useForm<VehicleForm>();
const toggleSwitch = () => {
if (isEnabled) {
unregister('trailerEnrolment');
unregister('trailerPlate');
}
clearErrors();
setIsEnabled(prev => !prev)
};
Feel free to upvote if I was helpful.

Get value of input controls which were created dynamically

In my React TypeScript project, I am dynamically creating multiple input controls like TextField, DatePicker, Checkbox, ComboBox etc... in a form like UI. On click on Submit, I want to get the value of each of the input controls. What's an effective way to do this? I can have an onChange event for each of the controls, but I was wondering if there is a better way to do this.
That's not a bad way to do it. You should probably be storing the values in the component's local state (i.e. setState) or a Redux/Mobx/whatever store if you have that.
That being said, if you have many controls and don't want to adds an individual handler for each one, Fabric components have mostly similar APIs for their onChange handlers, so you can have a single handler, and add an identifier to the element so that it's easier to store.
Something like:
class MyForm extends React.Component<MyFormProps, MyFormState> {
constructor(props: MyFormProps) {
super(props);
this.state = {
formFields: {...defaultFormValues} // you can imagine having an object of default values
};
}
private _onChangeHandler(ev: React.FormEvent<HTMLElement | HTMLInputElement>, newValue: any) => {
const formFields = {...this.state.formFields};
formFields[ev.target.dataset.id] = newValue;
this.setState({formFields});
}
public render() {
return (
<form>
<TextField data-id="formelem1" onChange={this._onChangeHandler} />
<TextField data-id="formelem2" onChange={this._onChangeHandler} />
<CheckBox data-id="checkbox1" onChange={this._onChangeHandler} />
</form>
);
}
}
Note that the one exception to this is the DatePicker because its onChange handler (onSelectDate) receives the new selected date as a single parameter, but you can easily add an if clause to handle this case.

React - Mobx Validation input Field

I have been searching for a MOBX validation on a input field, but I havent be able to find anything, I found "MobX-input" which requires a form but I dont have any form. another one that I found was "mobx-react-form" with ValidatorJs which again uses form. any hint or example would be appreciated . I just wanna be able to use it on plain input field
<Input placeholder="FirstName" type="text"
defaultValue={Contact.FirstName} onChange={(e) => handler(e)} />
Simple validation is pretty easy to create on your own with MobX. For a single field like this, a simple method for validating the function could look like this:
in the component we have an error field that only shows if the input has been submitted (which could be triggered by a button push or whatever)
return <div>
<input placeholder="FirstName" type="text"
defaultValue={Contact.FirstName} onChange={(e) => handler(e)} />
{submitted && <span className="error-message">{Contact.FirstNameError}</span>}
</div>;
In the observable class (I used the non-decorator style), we define the field as an observable, and an error message class as a computed value.
class Contact {
constructor() {
extendObservable({
submitted: false,
FirstName: observable(),
FirstNameError: computed(() => {
if(this.FirstName.length < 10) {
return 'First name must be at least 10 characters long';
}
// further validation here
return undefined;
})
})
}
}
You could easily add an extra hasError computed value that just checks to see if FirstNameError has a value.
This method scales to a few inputs. If you start having a bunch of them, then you'd want to look into an abstraction like a 3rd party library or something you write yourself to manage your validations. You could write a function to generate the computed properties you need based on a little configuration.