Validate function not called in redux-form - reactjs

I am using redux-form 6.3 version and in this validate function getting called. below is my code. Please check what is issue in code.
Also is there any need to do changes related to validation in actions
import React, { Component } from 'react';
import { Field, reduxForm, initialize } from 'redux-form';
import { connect } from 'react-redux';
import * as actions from '../../actions';
const renderField = field => (
<div className="form-group">
<label>{field.input.label}</label>
<input {...field.input} value={field.value} onChange={(e)=> console.log(e.target.value) } />
{field.touched && field.error && <div className="error">{field.error}</div>}
</div>
);
const renderSelect = field => (
<div>
<label>{field.input.label}</label>
<select {...field.input}/>
{field.touched && field.error && <div className="error">{field.error}</div>}
</div>
);
function validate(formProps) {console.log("vvv---", formProps);
const errors = {};
if (!formProps.firstName) {
errors.firstName = 'Please enter a first name';
}
if (!formProps.lastName) {
errors.lastName = 'Please enter a last name';
}
if (!formProps.email) {
errors.email = 'Please enter an email';
}
if (!formProps.phoneNumber) {
errors.phoneNumber = 'Please enter a phone number'
}
if(!formProps.sex) {
errors.sex = 'You must enter your sex!'
}
return errors;
}
class ReduxFormTutorial extends Component {
componentDidMount() {
this.handleInitialize();
}
handleInitialize() {
const initData = {
"firstName": "Puneet",
"lastName": "Bhandari",
"sex": "male",
"email": "test#gmail.com",
"phoneNumber": "23424234"
};
this.props.initialize(initData);
}
handleFormSubmit(formProps) {
//console.log(formProps);
this.state = { firstName : null };
this.props.submitFormAction(formProps);
}
//our other functions will go here
render() {
const { fields : [firstName, lastName], handleSubmit } = this.props;
return (
<div>
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<Field name="firstName" value="" type="text" component={renderField} label="First Name" />
<Field name="lastName" value="" type="text" component={renderField} label="Last Name"/>
<Field name="sex" component={renderSelect} label="Gender">
<option></option>
<option name="male">Male</option>
<option name="female">Female</option>
</Field>
<Field name="email" type="email" component={renderField} label="Email" />
<Field name="phoneNumber" type="tel" component={renderField} label="Phone Number"/>
<button action="submit">Save changes</button>
</form>
</div>
)
}
}
const form = reduxForm({
form: 'ReduxFormTutorial',
fields: [ 'firstName', 'lastName' ],
validate
});
function mapStateToProps(state) {
return {
user: state.user
};
}
export default connect(mapStateToProps, actions)(form(ReduxFormTutorial));

Related

Redux-form cannot submit

I'm creating my first Redux-form but the form doesn't add the info to database.
class UserInfo extends Component{
renderField(field) {
const { meta: { touched, error } } = field;
const className = `form-group ${touched && error ? "has-danger" : ""}`;
return (
<div className={className}>
<label>{field.label}</label>
<input className="form-control" type="text" {...field.input} />
<div className="text-help">
{touched ? error : ""}
</div>
</div>
);
}
onSubmit(values){
//this.props.addUser(values);
console.log(values);
}
render(){
const { handleSubmit, pristine, reset, submitting } = this.props;
return(
<div>
<div>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<div className='form-row'>
<Field label='Name' component={this.renderField} name='username' />
<Field label='Address' component={this.renderField }name='address' />
<Field label='Contact' component={this.renderField} name='contact' />
<Field label='Email'component={this.renderField} name='email' />
<button type="submit" className="btn btn-primary">Add new User</button>
</div>
</form>
</div>
</div>
);
}
}
function validate(values) {
const errors = {};
if (!values.uername) {
errors.username = 'Please enter a first name';
}
if (!values.address) {
errors.address = 'Please enter an address';
}
if (!values.contact) {
errors.contact = 'Please enter a phone number'
}
if (!values.email) {
errors.email = 'Please enter an email';
}
return errors;
}
export default reduxForm({
validate,
form: 'UserForm'
})(connect(null, { addUser })(UserInfo));
If I use console.log(values) in onSubmit function I don't get any output in the browser.I'm using createLogger to help with actions. And it shows type:
"##redux-form/SET_SUBMIT_FAILED"
I can't figure out what type of error this is.
Use developer tools(ctrl+shift+I), take redux-- state--form--'NameofReduxform'--syncErrors. Then, you might see some required fields.. You need to fill the fields to make the submit work. Hope this helps!

how to set init values on redux form

I am trying to set init values on a redux form load but it is not working for me. i have tried all 3 options from here . I have tried with dispatch and initialize in componentDidMount. also tried in export section at bottom of class. this one i was not sure how to put it in the connect part as i am using map functions. i placed it in the form section
class SecurityExemptionsNew extends Component {
constructor(props) {
super(props);
this.renderSelectField = this.renderSelectField.bind(this);
this.renderTextField = this.renderTextField.bind(this);
this.renderSelect2Field = this.renderSelect2Field.bind(this);
this.runOnce = false;
this.state = {
loaded: false,
isLoading: true,
searchable: true,
selectValue: { value: '0', label: 'All'},
selectMarketValue : "Group Enterprise Technology (GET)",
clearable: true,
rtl: false,
options: [
{ value: '0', label: 'All'}
],
toggleChecked: true,
lm_security_engineer: ''
};
}
omponentDidMount() {
this.passMetaBack;
this.props.dispatch(change('SecurityExemptionsNewForm', 'market', 'Group Enterprise Technology (GET)'));
this.props.initialize({ market: 'Group Enterprise Technology (GET)' });
}
renderSelectField(field) {
let options = [];
if (field.label == 'Type') {
options = this.populateOptions(this.exemptionType, 'name', 'name');
} else if (field.label == 'Market') {
options = this.populateOptions(this.markets, 'name', 'name');
} else if (field.label == 'Service Domain') {
options = this.populateOptions(this.serviceDomain, 'name', 'name');
} else if (field.label == 'Service/Project/Programme') {
options = this.populateOptions(this.servicesList, 'id', 'name');
options.unshift(
<option key="0" value="0" selected>
All
</option>
);
} else if (field.label == 'Comms Matrix') {
options.unshift(
<option key="0" value="0" selected>
All
</option>
);
} else if (field.label == 'Security Engineer') {
options = this.populateOptions(this.securityEngineerList, 'email', 'email');
options.unshift(
<option key="0" value="" selected>
--Select Engineer--
</option>
);
} else if (field.label == 'LM Security Engineer') {
options = this.populateOptions(this.securityEngineerLocalMarketList, 'email', 'email');
options.unshift(
<option key="0" value="" selected>
--Select Engineer--
</option>
);
} else if (field.label == 'Business Priority') {
options = this.populateOptions(this.businessPriority, 'name', 'name');
}
let id = "select_" + field.input.name;
return (
<div className="form-group">
<label className="control-label col-sm-2">{field.label}</label>
<div className="col-sm-10">
<select
id={id}
{...field.select}
name={field.input.name}
className="form-control form-control-inline"
type="select"
onChange={event => {
//props.input.onChange(event); // <-- Propagate the event
this.updateCommsMatrix(event.target.value);
}}
>
{options}
</select>
</div>
</div>
);
}
renderSelect2Field(field){
return(
<div className="form-group">
<label className="control-label col-sm-2">{field.label}</label>
<div className="col-sm-4">
<Async
name={field.input.name}
multi={false}
value={this.state.selectValue}
onChange={this.updateValue}
valueKey="value"
labelKey="label"
loadOptions={this.getCommsmatrices}
onValueClick={this.gotoCommsmatrix}
cache={false}
isLoading={this.state.isLoading}
optionRenderer={(option) => {return option.label;}}
/>
</div>
</div>
);
}
render() {
console.log(this);
if (!this.runOnce && this.props.isReady) {
this.runOnce = true;
this.initData();
}
const { handleSubmit } = this.props;
let form = 'Loading...';
if (this.state.loaded) {
let policiesTable = this.renderPolicies();
return (
<div className="container-fluid">
<form onSubmit={handleSubmit} className="form-horizontal">
<Field
label="Type"
loadFrom="exemptionType"
name="exemption_type"
component={this.renderSelectField}
/>
<Field
label="Market"
loadFrom="markets"
name="market"
component={this.renderSelectField}
/>
<Field
label="Service Domain"
loadFrom="serviceDomain"
name="service_domain"
component={this.renderSelectField}
type="select"
/>
<Field
label="Service/Project/Programme"
loadFrom="servicesList"
name="service_id"
component={this.renderSelectField}
type="select"
/>
<Field
label="Demand Ref"
name="demand_ref"
component={this.renderTextField}
type="text"
/>
<Field
label="Exemption Summary"
name="name"
component={this.renderTextField}
type="text"
/>
<Field
label="Exemption Description"
name="description"
component={this.renderTextareaField}
type="textarea"
/>
<div className="form-group">
<label className="control-label col-sm-2">Comms Matrix:</label>
<div className="col-sm-4">
<Async
multi={false}
value={this.state.selectValue}
onChange={this.updateValue}
valueKey="value"
labelKey="label"
loadOptions={this.getCommsmatrices}
onValueClick={this.gotoCommsmatrix}
cache={false}
/>
</div>
</div>
{policiesTable}
<Field
label="Requestor"
name="requestor"
component={this.renderTextField}
type="text"
readonly="readonly"
/>
<Field
label="Security Engineer"
loadFrom="securityEngineerList"
name="security_engineer"
component={this.renderSelectField}
type="select"
/>
{this.state.lm_security_engineer}
<Field
label="Link to Design Doc"
name="designdoc"
component={this.renderTextField}
type="text"
/>
<Field
label="Business Priority"
loadFrom="businessPriority"
name="business_priority"
component={this.renderSelectField}
type="select"
/>
<Field
label="Expiry date (dd-MMM-yy)"
name="expiry_date"
component={this.renderTextField}
type="text"
/>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button id="btnSubmit" type="submit" name="btnSubmit" className="btn btn-vodafone hidden-print">Submit</button>
</div>
</div>
</form>
</div>
);
}
return <div className="container-fluid">{form}</div>;
}
}
function mapStateToProps(state) {
return {
securityExemptions: state.securityExemptions,
commsmatrices: state.commsmatrices
};
}
//Anything returned from this function will end up as props
//on the User container
function mapDispatchToProps(dispatch) {
// Whenever getUser is called, the result should be passed
// to all our reducers
//return {
//actions: bindActionCreators(Object.assign({}, fetchServices, checkServiceEditable ), dispatch)
//};
return bindActionCreators(
{
fetchExemptionType,
fetchMarkets,
fetchServiceDomains,
fetchServicesList,
fetchCommsmatricesByService,
fetchExemptionsForCommsmatrix,
fetchSecurityEngineerList,
fetchBusinessPriorityList
},
dispatch
);
}
SecurityExemptionsNew = connect(mapStateToProps, mapDispatchToProps)(
SecurityExemptionsNew
);
//Decorate the form component
export default reduxForm({
form: 'SecurityExemptionsNewForm', // a unique name for this form
initialValues: { service_domain: 'Corporate (Internal/External)' }
})(SecurityExemptionsNew);
update
Having not being able to use redux-form to init the default values, i just used the default values tag with state
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import FontAwesome from 'react-fontawesome';
import { isServiceName, isServiceRef } from '../../scripts/validation';
import {
fetchExemptionType,
fetchMarkets,
fetchServiceDomains,
fetchServicesList,
fetchExemptionsForCommsmatrix,
fetchSecurityEngineerList,
fetchBusinessPriorityList
} from '../../actions/security';
import { fetchCommsmatricesByService } from '../../actions/commsmatrices';
import axios from 'axios';
import { Field, reduxForm, change } from 'redux-form';
import PropTypes from 'prop-types';
import { Select, Async } from "react-select";
import 'react-select/dist/react-select.css';
class SecurityExemptionsNew extends Component {
constructor(props) {
super(props);
this.handleSaveBtnClick = this.handleSaveBtnClick.bind(this);
this.handleShowError = this.handleShowError.bind(this);
this.initData = this.initData.bind(this);
this.renderSelectField = this.renderSelectField.bind(this);
this.renderTextField = this.renderTextField.bind(this);
this.updateCommsMatrix = this.updateCommsMatrix.bind(this);
this.renderSelect2Field = this.renderSelect2Field.bind(this);
this.clearValue = this.clearValue.bind(this);
this.updateValue = this.updateValue.bind(this);
this.getCommsmatrices = this.getCommsmatrices.bind(this);
this.fnToggleCheckboxes = this.fnToggleCheckboxes.bind(this);
this.handleCheckedValues = this.handleCheckedValues.bind(this);
this.meta = {
title: 'Request Exemption',
description: 'This section allows you to request an exemption'
};
this.passMetaBack = this.passMetaBack.bind(this);
this.runOnce = false;
this.state = {
loaded: false,
isLoading: true,
searchable: true,
selectValue: { value: '0', label: 'All'},
selectMarketValue : "Group Enterprise Technology (GET)",
clearable: true,
rtl: false,
options: [
{ value: '0', label: 'All'}
],
toggleChecked: true,
lm_security_engineer: '',
select_exemption_type: 'Security',
select_market: 'Group Enterprise Technology (GET)',
select_service_domain: 'Corporate (Internal/External)',
select_service_id: '0',
select_security_engineer: null,
select_business_priority: 'Low'
};
this.exemptionType = {};
this.markets = {};
this.serviceDomain = {};
this.servicesList = {};
this.matrices = {};
this.securityEngineerList = {};
this.securityEngineerLocalMarketList = {}
this.businessPriority = {}
this.tableOptions = {
paginationShowsTotal: false,
sizePerPageList: [ {
text: '10', value: 10
}, {
text: '50', value: 50
}, {
text: '100', value: 100
}
],
};
this.checkedValues = [];
}
componentDidMount() {
console.log("componentDidMount");
this.passMetaBack;
this.props.initialize({ market: 'Group Enterprise Technology (GET)' });
this.props.dispatch(change('SecurityExemptionsNewForm', 'market', 'Group Enterprise Technology (GET)'));
}
passMetaBack = () => {
this.props.passMetaBack(this.meta);
};
renderSelectField(field) {
let defaultValue = this.state['select_'+field.input.name];
let options = [];
if (field.label == 'Type') {
options = this.populateOptions(this.exemptionType, 'name', 'name');
} else if (field.label == 'Market') {
options = this.populateOptions(this.markets, 'name', 'name');
} else if (field.label == 'Service Domain') {
options = this.populateOptions(this.serviceDomain, 'name', 'name');
} else if (field.label == 'Service/Project/Programme') {
options = this.populateOptions(this.servicesList, 'id', 'name');
options.unshift(
<option key="0" value="0">
All
</option>
);
} else if (field.label == 'Comms Matrix') {
options.unshift(
<option key="0" value="0">
All
</option>
);
} else if (field.label == 'Security Engineer') {
options = this.populateOptions(this.securityEngineerList, 'email', 'email');
options.unshift(
<option key="0" value="">
--Select Engineer--
</option>
);
} else if (field.label == 'LM Security Engineer') {
options = this.populateOptions(this.securityEngineerLocalMarketList, 'email', 'email');
options.unshift(
<option key="0" value="">
--Select Engineer--
</option>
);
} else if (field.label == 'Business Priority') {
options = this.populateOptions(this.businessPriority, 'name', 'name');
}
let id = "select_" + field.input.name;
return (
<div className="form-group">
<label className="control-label col-sm-2">{field.label}</label>
<div className="col-sm-10">
<select
id={id}
{...field.select}
name={field.input.name}
className="form-control form-control-inline"
type="select"
onChange={event => {
//props.input.onChange(event); // <-- Propagate the event
this.updateCommsMatrix(event.target.value);
}}
defaultValue={defaultValue}
>
{options}
</select>
</div>
</div>
);
}
renderSelect2Field(field){
return(
<div className="form-group">
<label className="control-label col-sm-2">{field.label}</label>
<div className="col-sm-4">
<Async
name={field.input.name}
multi={false}
value={this.state.selectValue}
onChange={this.updateValue}
valueKey="value"
labelKey="label"
loadOptions={this.getCommsmatrices}
onValueClick={this.gotoCommsmatrix}
cache={false}
isLoading={this.state.isLoading}
optionRenderer={(option) => {return option.label;}}
/>
</div>
</div>
);
}
renderTextField(field) {
let value = '';
let readonly = false
if (field.label == 'Requestor') {
value = this.props.activeUser.email;
readonly = true;
}
return (
<div className="form-group">
<label className="control-label col-sm-2">{field.label}</label>
<div className="col-sm-10">
<input
name={field.input.name}
className="form-control form-control-inline"
type="text"
{...field.text}
defaultValue={value}
readOnly={readonly}
/>
</div>
</div>
);
}
renderTextareaField(field) {
return (
<div className="form-group">
<label className="control-label col-sm-2">{field.label}</label>
<div className="col-sm-10">
<textarea
name={field.input.name}
className="form-control form-control-inline"
type="textarea"
{...field.text}
/>
</div>
</div>
);
}
handleCheckedValues({target}){
if (target.checked){
target.setAttribute('checked', true);
this.checkedValues.push({id:$(target).val()});
}else{
target.removeAttribute('checked');
let arr = this.checkedValues.filter(function(item) {
return item.id !== $(target).val()
})
this.checkedValues = arr;
}
}
render() {
console.log(this);
if (!this.runOnce && this.props.isReady) {
this.runOnce = true;
this.initData();
}
const { handleSubmit } = this.props;
let form = 'Loading...';
if (this.state.loaded) {
let policiesTable = this.renderPolicies();
return (
<div className="container-fluid">
<form onSubmit={handleSubmit} className="form-horizontal">
<Field
label="Type"
loadFrom="exemptionType"
name="exemption_type"
component={this.renderSelectField}
/>
<Field
label="Market"
loadFrom="markets"
name="market"
component={this.renderSelectField}
/>
<Field
label="Service Domain"
loadFrom="serviceDomain"
name="service_domain"
component={this.renderSelectField}
type="select"
/>
<Field
label="Service/Project/Programme"
loadFrom="servicesList"
name="service_id"
component={this.renderSelectField}
type="select"
/>
<Field
label="Demand Ref"
name="demand_ref"
component={this.renderTextField}
type="text"
/>
<Field
label="Exemption Summary"
name="name"
component={this.renderTextField}
type="text"
/>
<Field
label="Exemption Description"
name="description"
component={this.renderTextareaField}
type="textarea"
/>
<div className="form-group">
<label className="control-label col-sm-2">Comms Matrix:</label>
<div className="col-sm-4">
<Async
multi={false}
value={this.state.selectValue}
onChange={this.updateValue}
valueKey="value"
labelKey="label"
loadOptions={this.getCommsmatrices}
onValueClick={this.gotoCommsmatrix}
cache={false}
/>
</div>
</div>
{policiesTable}
<Field
label="Requestor"
name="requestor"
component={this.renderTextField}
type="text"
readonly="readonly"
/>
<Field
label="Security Engineer"
loadFrom="securityEngineerList"
name="security_engineer"
component={this.renderSelectField}
type="select"
/>
{this.state.lm_security_engineer}
<Field
label="Link to Design Doc"
name="designdoc"
component={this.renderTextField}
type="text"
/>
<Field
label="Business Priority"
loadFrom="businessPriority"
name="business_priority"
component={this.renderSelectField}
type="select"
/>
<Field
label="Expiry date (dd-MMM-yy)"
name="expiry_date"
component={this.renderTextField}
type="text"
/>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button id="btnSubmit" type="submit" name="btnSubmit" className="btn btn-vodafone hidden-print">Submit</button>
</div>
</div>
</form>
</div>
);
}
return <div className="container-fluid">{form}</div>;
}
}
function mapStateToProps(state) {
return {
securityExemptions: state.securityExemptions,
commsmatrices: state.commsmatrices
};
}
//Anything returned from this function will end up as props
//on the User container
function mapDispatchToProps(dispatch) {
// Whenever getUser is called, the result should be passed
// to all our reducers
//return {
//actions: bindActionCreators(Object.assign({}, fetchServices, checkServiceEditable ), dispatch)
//};
return bindActionCreators(
{
fetchExemptionType,
fetchMarkets,
fetchServiceDomains,
fetchServicesList,
fetchCommsmatricesByService,
fetchExemptionsForCommsmatrix,
fetchSecurityEngineerList,
fetchBusinessPriorityList
},
dispatch
);
}
SecurityExemptionsNew = connect(mapStateToProps, mapDispatchToProps)(
SecurityExemptionsNew
);
function validate (values) {
console.log(values);
const errors = {};
if(!values.name){
errors.name = "Enter summary";
}
return errors;
}
//Decorate the form component
export default reduxForm({
form: 'SecurityExemptionsNewForm', // a unique name for this form
validate,
initialValues: { market: 'Group Enterprise Technology (GET)', service_domain: 'Corporate (Internal/External)' }
})(SecurityExemptionsNew);

How get values from a select/option field in redux-form?

I am trying to get the values from my second form. It renders some select options and when I hit the delete button it just returns an empty object. How do I get the value from the options. With the normal input fields it would pass values with the name.
For example if I had an input type="text" name="email", when I would submit this it would give my an object like:
{email: "some string"}
Here is the code:
import React , { Component } from 'react';
// import * as actions from '../actions';
import { reduxForm, Field } from 'redux-form';
import {connect} from 'react-redux';
import {postBooks, deleteBook} from '../../actions/booksActions';
class BooksForm extends Component {
renderField(field) {
const { meta: {touched, error} } = field;
const className = `form-group ${touched && error ? 'has-danger' : ''}`;
return (
<div className={className}>
<label className="control-label"><strong>{field.label}:</strong></label>
<input
className="form-control"
type={field.type}
{...field.input}
/>
<div className="text-help">
{ touched ? error : ''}
</div>
</div>
);
}
renderSelectField(field) {
const bookList = _.map(field.options, (book) => {
return (
<option key={book._id}>{book.title}</option>
)
});
return(
<div className="form-group">
<label htmlFor="sel1" className="control-label">{field.label}</label>
<select className="form-control" id="sel1">
{bookList}
</select>
</div>
);
}
onSubmit(values) {
this.props.postBooks(values);
}
onDelete(values) {
console.log(values);
}
render() {
const {handleSubmit} = this.props;
return (
<div>
<div className="well">
<form className="panel" onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<div className="panel-body">
<Field
label="Title"
name="title"
type="text"
component={this.renderField}
/>
<Field
label="Description"
name="description"
type="text"
component={this.renderField}
/>
<Field
label="Price"
name="price"
type="text"
component={this.renderField}
/>
<button className="btn btn-primary">Save Book</button>
</div>
</form>
</div>
<form className="Panel" onSubmit={handleSubmit(this.onDelete.bind(this))}>
<div className="panel-body">
<Field
label="Select Book"
name="selectedBook"
options={this.props.books}
component={this.renderSelectField}
/>
<button className="btn btn-danger">Delete</button>
</div>
</form>
</div>
);
}
}
function validate(values) {
const errors = {};
return errors;
}
function mapStateToProps(state) {
return {
books: state.books
}
}
export default reduxForm({
validate,
form: 'bookForm'
})(connect(mapStateToProps, {postBooks, deleteBook})(BooksForm));
In renderSelectField I needed to add {...field.input} into the select to allow redux-form to monitor it.
<select className="form-control" id="sel1" {...field.input}>

Redux-form onSubmit nothing happens

I would like to ask, what I miss on my code. It seems submitForm function is not working/triggering when I submit the form. I can't get values from my form fields. Here's my code:
import React from 'react';
import { reduxForm,reset, Field } from 'redux-form';
class FormProfile extends React.Component {
submitForm(formProps){
console.log(formProps);
}
render(){
const { error, handleSubmit } = this.props;
return (
<form onSubmit={this.submitForm.bind(this)}>
<Row>
<Col lg={6}>
<Field name="name" type="text" component={TextBoxComponent} placeholder="Compay Name" label="* Company Name" required />
<Field name="website" type="text" component={TextBoxComponent} placeholder="www.yourdomain.com" label="Website" />
<Field name="email" type="text" component={TextBoxComponent} placeholder="How can we contact your Company" label="* Contact Email" required />
</Col>
</Row>
</form>
);
}
}
const form = reduxForm({
form: 'CreateCompanyProfileForm',
validate
});
function validate(formProps){
const error = {};
return error;
}
export default (form(FormProfile));
TextBox Componen
import React from "react";
class TextBoxComponent extends React.Component {
render(){
return (
<div className="form-group">
<label className="control-label">{this.props.label}</label>
{ this.props.sublabel !== undefined ?
<em className="text-info"> { this.props.sublabel }</em>
:null}
<input { ...this.props } type={this.props.type} placeholder={this.props.placeholder} className="form-control"/>
{ this.props.required && <span className="text-error"></span> }
</div>
);
}
}
export default TextBoxComponent;
You should modify this line:
<form onSubmit={this.submitForm.bind(this)}>
to:
<form onSubmit={handleSubmit}>
then you can remove:
submitForm(formProps){
console.log(formProps);
}
Then you can create a new component to wrap redux form component:
class SamplePage extends React.Component {
handleSubmit = (values) => {
// Do something with the form values
console.log(values);
}
render() {
return (
<FormProfile onSubmit={this.handleSubmit} />
);
}
}
Anyway, you should check the example from Redux-form docs: http://redux-form.com/6.5.0/docs/GettingStarted.md/

want to load initial Values in Redux Form

i am trying to load the initial value in from but couldn't do this, i am using redux-from, i set the profile data in redux store and can access the data through the props(console them) but can't able to show in the form input. i am trying to replicate this redux-from example. but couldn' able to continue it.
below is the code.
import React from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { required, email, maxLength25 } from '../utils/validations';
import { renderField,
renderSelectField,
renderRadioField,
renderTextAreaField,
renderCheckboxField
} from '../utils/textFieldGroup';
import countries from '../utils/countryList';
import { profileUpdate, profile } from '../actions/user';
const validateAndUpdateRecords = (values, dispatch) => {
return dispatch(profileUpdate(values))
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
}
class ProfileForm extends React.Component {
componentWillMount(dispatch){
console.log('mount');
this.props.fetchProfile();
}
render(){
const { handleSubmit, submitSucceeded, error, profile } = this.props
console.log('prof',profile);
return (
<div>
<h1>Profile Page</h1>
<form onSubmit={handleSubmit(validateAndUpdateRecords)}>
<div className={typeof error!='undefined'?'show alert alert-danger': 'hidden'}>
<strong>Error!</strong> {error}
</div>
<Field name="fname" type="text" component={renderField} label="First Name"
validate={[ required, maxLength25 ]}
/>
<Field name="lname" type="text" component={renderField} label="Last Name"
validate={[ required, maxLength25 ]}
/>
<Field component={renderRadioField} name="gender" label="Gender" options={[
{ title: 'Male', value: 'male' },
{ title: 'Female', value: 'female' }
]} validate={ required } />
<Field name="country" type="text" data={countries} component={renderSelectField} label="Country"
validate={[ required ]}
/>
<Field name="about_us" type="text" component={renderTextAreaField} label="About Us"
validate={[ required ]}
/>
<Field name="newsletter" type="checkbox" component={renderCheckboxField} label="Newsletter"
validate={[ required ]}
/>
<p>
<button type="submit" disabled={submitSucceeded} className="btn btn-primary btn-lg">Submit</button>
</p>
</form>
</div>
)
}
}
ProfileForm = reduxForm({
form:'profile'
})(ProfileForm)
ProfileForm = connect(
state => ({
initialValues: state.user.profile
})
)(ProfileForm)
export default ProfileForm;
//text field
export const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
<div className={classnames('form-group', { 'has-error':touched && error })}>
<label className="control-label">{label}</label>
<div>
<input {...input} placeholder={label} type={type} className="form-control"/>
{touched && ((error && <span className="help-block">{error}</span>))}
</div>
</div>
)
Thanks in advance
Finally i figure out the solutions. below is the solutions. We need to add enableReinitialize : true as mentioned below. If our initialValues prop gets updated, form will update too.
ProfileForm = reduxForm({
form:'profile',
enableReinitialize : true
})(ProfileForm)

Resources