Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redux-form how to load data for editing

I am working with redux-form and it seems confusing me to load initial data for edit form but the data is not being validated on submit. I have managed to pass and load data into the fields but that seems not loading into the form props etc. Please see the following piece of code and let me know if need something more.

Form_Bayan.js

import React, {Component, PropTypes} from "react";  
import {browserHistory} from "react-router";        
import {reduxForm, Field} from "redux-form";

import {MyCustomInput, MySimpleInput, MyCustomSelect} from "./__form_field_components";

import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import {
    ADMIN_FETCH_AUTOSUGGESTS_Lbl,
    adminFetchAutoSuggestCats_act,
    ADMIN_GETCATID_BYNAME_Lbl,
    adminGetCatIdByName_act,
    ADMIN_ADDNEWBAYAAN_Lbl,
    adminAddNewBayaan_act,
    adminFetchArticlesByCat_act,
    adminUpdateBayaan_act
} from "../../actions/adminActionCreators";
import _ from "lodash";


class NewBayanForm extends Component {

    constructor(props) {
        super(props);       

        this.state = {
            submitButtonMeta: {
                btnTitle: "Save",
                btnClass: "btn btn-default",
                btnIcon: null,
                disabled: false
            },
            globalMessage: {                        // set when an action is performed by ActionCreation+Reducer and a message is returned
                message: "",
                className: ""
            },
            tempData: {

                the_bayaansMainCat_id: this.props.associatedMainCatId,              // being passed from parent component to avoide redundent declaration
                the_autoSuggestCatList: [],
                slug: "",
                the_catId: null
            }
        };
    }

    resetMessageState() {
        var noMsg = {message: "", className: ""};
        this.setState({globalMessage: noMsg});
    }

    componentDidMount() {
        this.props.adminFetchAutoSuggestCats_act(this.state.tempData.the_bayaansMainCat_id);
    }

    doSubmit(props) {

        var newBayanObj = {
            item_title: props.titleTxt,
            item_slug: this.state.tempData.slug,
            content: props.videoIdTxt,
            picture: "",
            attachment: "",
            media_path: "https://www.youtube.com/watch?v=" + props.videoIdTxt,
            reference: "",
            tag_keywords: props.keywordsTxt,
            author_name: props.authorTxt,
            cat_id: this.state.tempData.the_catId
        };


            this.props.adminUpdateBayaan_act(newBayaanObj)
                .then(() => {
                    this.props.adminFetchArticlesByCat_act(this.props.associatedMainCatId)
                        .then(() => {
                            this.props.toggleViewFunction();        // comming from Parent Class (bayaansPage)
                        });
                });


    }


    fetchCategoryId(value) {
        // make API call to fetch / generate category ID for this post
        this.props.adminGetCatIdByName_act(value, this.state.tempData.the_bayaansMainCat_id);               // '1': refers to look up under 'Bayaans' parent category for the specified category name
    }

    // will always receive and triggers when there are 'new props' and not old/same props


    render() {    // rendering Edit form
        const {handleSubmit} = this.props;
        console.log('<NewBayanForm> (render_editForm) this.props:', this.props);
        return (
            <div className="adminForm">
                <form onSubmit={handleSubmit(this.doSubmit.bind(this))}>
                    <div className="col-sm-6">
                        <div className="row">
                            <div className="col-sm-5"><label>Title:</label></div>
                            <div className="col-sm-7"><Field name="titleTxt" component={MySimpleInput}
                                                             defaultValue={this.props.name} type="text"
                                                             placeholder="Enter Title"/></div>
                        </div>
                        <div className="row">
                            <div className="col-sm-5"><label>Slug:</label></div>
                            <div className="col-sm-7">{this.state.tempData.slug || this.props.slug} <input
                                type="hidden" name="slugTxt" value={this.state.tempData.slug}/></div>
                        </div>
                        <div className="row">
                            <div className="col-sm-5"><label>Select Category:</label></div>
                            <div className="col-sm-7"><Field name="catTxt" component={MyCustomSelect}
                                                             defaultValue={this.props.category_name} type="text"
                                                             placeholder="Select or Type a New"
                                                             selectableOptionsList={this.state.tempData.the_autoSuggestCatList}
                                                             onSelectionDone={ this.fetchCategoryId.bind(this) }/>
                                <input type="hidden" name="catIdTxt"
                                       value={this.state.tempData.the_catId || this.props.category_id}/>
                            </div>
                        </div>
                    </div>
                    <div className="col-sm-6">
                        <div className="row">
                            <div className="col-sm-5"><label>Youtube Video ID:</label></div>
                            <div className="col-sm-7"><Field name="videoIdTxt" component={MySimpleInput}
                                                             defaultValue={this.props.content} type="text"
                                                             placeholder="TsQs9aDKwrw"/></div>
                            <div className="col-sm-12 hint"><b>Hint: </b> https://www.youtube.com/watch?v=<span
                                className="highlight">TsQs9aDKwrw</span></div>
                        </div>
                        <div className="row">
                            <div className="col-sm-5"><label>Author/Speaker:</label></div>
                            <div className="col-sm-7"><Field name="authorTxt" component={MySimpleInput}
                                                             defaultValue={this.props.author} type="text"/></div>
                        </div>
                        <div className="row">
                            <div className="col-sm-5"><label>Tags/Keywords:</label></div>
                            <div className="col-sm-7"><Field name="keywordsTxt" component={MySimpleInput}
                                                             defaultValue={this.props.tag_keywords} type="text"/>
                            </div>
                        </div>
                    </div>
                    <div className="row">
                        <div className={this.state.globalMessage.className}>{this.state.globalMessage.message}</div>
                    </div>
                    <div className="buttonControls">
                        <a className="cancelBtn" onClick={this.props.toggleViewFunction}>Cancel</a>
                        <button className={this.state.submitButtonMeta.btnClass}
                                disabled={this.state.submitButtonMeta.disabled}>
                            {this.state.submitButtonMeta.btnTitle}</button>
                    </div>
                </form>
            </div>
        );
    }


}

function validate(values) { // Validate function being called on Blur
    const errors = {};
    if (!values.titleTxt)
        errors.titleTxt = "Enter Title";
    if (!values.catTxt)
        errors.catTxt = "Select/Enter a Category";
    if (!values.videoIdTxt)
        errors.videoIdTxt = "Enter youtube video ID (follow the provided hint)";
    if (!values.keywordsTxt)
        errors.keywordsTxt = "Enter keywords (will help in search)";


    return errors;
}


// ReduxForm decorator 
const newBayanFormAdmin_reduxformObj = reduxForm({
    form: "newBayanFormAdmin",  // any unique name of our form
    validate                // totally equivelent to-->  validate: validate
});


function mapStateToProps({siteEssentials}, ownProps) {
    // 1st param is related to our Redux State, 2nd param relates to our own component props
    var initialValues = {
        titleTxt: ownProps.name,
        slugTxt: ownProps.slug,
        catTxt: ownProps.category_name,
        catIdTxt: ownProps.category_id,
        videoIdTxt: ownProps.content,
        authorTxt: ownProps.author,
        keywordsTxt: ownProps.tag_keywords
    };
    return ({siteEssentials}, initialValues);
};

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        adminFetchAutoSuggestCats_act,
        adminGetCatIdByName_act,
        adminAddNewBayaan_act,
        adminFetchArticlesByCat_act
    }, dispatch);
};


NewBayanForm = connect(mapStateToProps, mapDispatchToProps) (newBayanFormAdmin_reduxformObj(NewBayanForm));

export default NewBayanForm;
like image 457
Nah Avatar asked Feb 03 '17 10:02

Nah


1 Answers

try initialValues for more details

inside reduxform :

export default NewBayanForm = reduxForm({ form: 'NewBayanForm', initialValues: {
  name: "abc",
  email: "[email protected]",
  phoneNo: "1234567890"
} })(NewBayanForm)

or

<NewBayanForm initialValues={yourObject} />
like image 85
ramamoorthy_villi Avatar answered Sep 28 '22 16:09

ramamoorthy_villi