Datatble crud

UI Components for React
Post Reply
FelipeProjeto
Posts: 20
Joined: 24 Jun 2019, 20:26

31 Aug 2020, 20:36

Good afternoon, I'm using primereact's datatable crud, but I'm not able to edit and delete the data from the table and database. Can someone help me?
I'm connected to a js and mongodb api node js.

Code: Select all

import React, {Component} from 'react';
import classNames from 'classnames';
import {DataTable} from 'primereact/datatable';
import {Column} from 'primereact/column';
import Services from '../../services/services';
import {Toast} from 'primereact/toast';
import {Button} from 'primereact/button';
import {Rating} from 'primereact/rating';
import {Toolbar} from 'primereact/toolbar';
import {InputTextarea} from 'primereact/inputtextarea';
import {RadioButton} from 'primereact/radiobutton';
import {InputNumber} from 'primereact/inputnumber';
import {Dialog} from 'primereact/dialog';
import {InputText} from 'primereact/inputtext';
import api from "../../services/services";


export default class Disciplina extends Component {

    emptyDisciplina = {
        _id: '',
        nome: '',
        codigo: '',
        eletiva: '',
        pos: '',

    };

    constructor(props) {
        super(props);

        this.state = {
            disciplinas: [],
            disciplinasInfo: {},
            disciplinaDialog: false,
            deleteDisciplinaDialog: false,
            deleteDisciplinasDialog: false,
            disciplina: this.emptyDisciplina,
            selectedDisciplinas: null,
            submitted: false,
            globalFilter: null
        };

        this.services = new Services();
        this.leftToolbarTemplate = this.leftToolbarTemplate.bind(this);
        this.rightToolbarTemplate = this.rightToolbarTemplate.bind(this);
        this.ratingBodyTemplate = this.ratingBodyTemplate.bind(this);
        this.statusBodyTemplate = this.statusBodyTemplate.bind(this);
        this.actionBodyTemplate = this.actionBodyTemplate.bind(this);

        this.openNew = this.openNew.bind(this);
        this.hideDialog = this.hideDialog.bind(this);
        this.saveDisciplina = this.saveDisciplina.bind(this);
        this.editDisciplina = this.editDisciplina.bind(this);
        this.confirmDeleteDisciplina = this.confirmDeleteDisciplina.bind(this);
        this.deleteDisciplina = this.deleteDisciplina.bind(this);
        this.confirmDeleteSelected = this.confirmDeleteSelected.bind(this);
        this.deleteSelectedDisciplinas = this.deleteSelectedDisciplinas.bind(this);
        this.onInputChange = this.onInputChange.bind(this);
        this.onInputNumberChange = this.onInputNumberChange.bind(this);
        this.hideDeleteDisciplinaDialog = this.hideDeleteDisciplinaDialog.bind(this);
        this.hideDeleteDisciplinasDialog = this.hideDeleteDisciplinasDialog.bind(this);

    }

    componentDidMount() {
        this.loadDisciplinas();
        this.loadDisciplinasEdit();
    }

    loadDisciplinas = async (page = 1) => {
        const response = await api.get(`/disciplinas`);
        const {docs, ...disciplinasInfo} = response.data;
        this.setState({disciplinas: docs, disciplinasInfo});
    };


    openNew() {
        this.setState({
            disciplina: this.emptyDisciplina,
            submitted: false,
            disciplinaDialog: true
        });
    }

    hideDialog() {
        this.setState({
            submitted: false,
            disciplinaDialog: false
        });
    }

    hideDeleteDisciplinaDialog() {
        this.setState({deleteDisciplinaDialog: false});
    }

    hideDeleteDisciplinasDialog() {
        this.setState({deleteDisciplinasDialog: false});
    }

    saveDisciplina() {
        let state = {submitted: true};

        let disciplinas = [...this.state.disciplinas];
        let disciplina = {...this.state.disciplina};

        fetch("http://localhost:4000/sispad/disciplinas", {
            method: "post",
            body: JSON.stringify(this.state.disciplina),
            headers: {
                "Content-Type": "application/json"
            }
        })
        disciplinas.push(disciplina);
        this.toast.show({severity: 'success', summary: 'Successful', detail: 'Product Created', life: 3000});

        state = {
            ...state,
            disciplinas,
            disciplinaDialog: false,
            disciplina: this.emptyDisciplina
        };

        this.setState(state);
    }


    async loadDisciplinasEdit() {
        const {id} = this.props.match.params;
        const response = await api.get(`/disciplinas/${id}`);
        this.setState({disciplina: response.data});
    }

    updateDisciplina = () => {
        let state = {submitted: true};
        let disciplinas = [...this.state.disciplinas];
        let disciplina = {...this.state.disciplina};
        const {id} = this.props.match.params;

        fetch(`http://localhost:4000/sispad/disciplinas/${id}`, {
            method: "put",
            id: id,
            body: JSON.stringify(this.state.disciplina),
            headers: {
                "Content-Type": "application/json"
            }
        })
        disciplinas.push(disciplina);
        this.toast.show({severity: 'success', summary: 'Successful', detail: 'Product Updated', life: 3000});


        state = {
            ...state,
            disciplinaEditDialog: false,
            disciplina: this.emptyDisciplina
        };


        this.setState(state);
    }


    editDisciplina(disciplina) {
        this.setState({
            disciplina: {...disciplina},
            disciplinaEditDialog: true
        });
    }

    confirmDeleteDisciplina(disciplina) {
        this.setState({
            disciplina,
            deleteDisciplinaDialog: true
        });
    }

    async componentDidMountDelete() {
        const {id} = this.props.match.params;
        const response = await api.get(`/disciplinas/${id}`);
        this.setState({disciplina: response.data});
    }

    async deleteDisciplina() {

        this.componentDidMountDelete();
        this.setState({
            deleteDisciplinaDialog: false,
            disciplina: this.emptyDisciplina
        });
        this.toast.show({severity: 'success', summary: 'Successful', detail: 'Product Deleted', life: 3000});
    }


    confirmDeleteSelected() {
        this.setState({deleteDisciplinasDialog: true});
    }

    deleteSelectedDisciplinas() {
        let disciplinas = this.state.disciplinas.filter(val => !this.state.selectedDisciplinas.includes(val));
        this.setState({
            disciplinas,
            deleteDisciplinasDialog: false,
            selectedDisciplinas: null
        });
        this.toast.show({severity: 'success', summary: 'Successful', detail: 'Products Deleted', life: 3000});
    }


    onInputChange(e, name) {
        const val = (e.target && e.target.value) || '';
        let disciplina = {...this.state.disciplina};
        disciplina[`${name}`] = val;

        this.setState({disciplina});
    }

    onInputNumberChange(e, name) {
        const val = e.value || 0;
        let disciplina = {...this.state.disciplina};
        disciplina[`${name}`] = val;

        this.setState({disciplina});
    }

    leftToolbarTemplate() {
        return (
            <>
                <Button label="New" icon="pi pi-plus" className="p-button-success p-mr-2" onClick={this.openNew}/>
                <Button label="Delete" icon="pi pi-trash" className="p-button-danger"
                        onClick={this.confirmDeleteSelected}
                        disabled={!this.state.selectedDisciplinas || !this.state.selectedDisciplinas.length}/>
            </>
        )
    }

    rightToolbarTemplate() {
        return (
            <>

            </>
        )
    }


    ratingBodyTemplate(rowData) {
        return <Rating value={rowData.rating} readonly cancel={false}/>;
    }

    statusBodyTemplate(rowData) {
        return <span
            className={`product-badge status-${rowData.inventoryStatus.toLowerCase()}`}>{rowData.inventoryStatus}</span>;
    }

    actionBodyTemplate(rowData) {
        return (
            <>
                <Button icon="pi pi-pencil" className="p-button-rounded p-button-success p-mr-2"
                        onClick={() => this.editDisciplina(rowData)}/>
                <Button icon="pi pi-trash" className="p-button-rounded p-button-warning"
                        onClick={() => this.confirmDeleteDisciplina(rowData)}/>
            </>
        );
    }

    render() {
        const header = (
            <div className="table-header">
                <h5 className="p-m-0">Manage Products</h5>
                <span className="p-input-icon-left">
                    <i className="pi pi-search"/>
                    <InputText type="search" onInput={(e) => this.setState({globalFilter: e.target.value})}
                               placeholder="Search..."/>
                </span>
            </div>
        );
        const disciplinaDialogFooter = (
            <>
                <Button label="Cancel" icon="pi pi-times" className="p-button-text" onClick={this.hideDialog}/>
                <Button label="Save" icon="pi pi-check" className="p-button-text" onClick={this.saveDisciplina}/>
            </>
        );
        const disciplinaDialogFooterUpdate = (
            <>
                <Button label="Cancel" icon="pi pi-times" className="p-button-text" onClick={this.hideDialog}/>
                <Button label="Save" icon="pi pi-check" className="p-button-text" onClick={this.updateDisciplina}/>
            </>
        );
        const deleteDisciplinaDialogFooter = (
            <>
                <Button label="No" icon="pi pi-times" className="p-button-text"
                        onClick={this.hideDeleteDisciplinaDialog}/>
                <Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={this.deleteDisciplina}/>
            </>
        );
        const deleteDisciplinasDialogFooter = (
            <>
                <Button label="No" icon="pi pi-times" className="p-button-text"
                        onClick={this.hideDeleteDisciplinasDialog}/>
                <Button label="Yes" icon="pi pi-check" className="p-button-text"
                        onClick={this.deleteSelectedDisciplinas}/>
            </>
        );

        return (
            <div className="datatable-crud-demo">
                <Toast ref={(el) => this.toast = el}/>

                <div className="card">
                    <Toolbar className="p-mb-4" left={this.leftToolbarTemplate}
                             right={this.rightToolbarTemplate}></Toolbar>

                    <DataTable ref={(el) => this.dt = el} value={this.state.disciplinas}
                               selection={this.state.selectedDisciplinas}
                               onSelectionChange={(e) => this.setState({selectedDisciplinas: e.value})}
                               dataKey="{id}" paginator rows={10} rowsPerPageOptions={[5, 10, 25]}
                               paginatorTemplate="CurrentPageReport FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown"
                               currentPageReportTemplate="Showing {first} to {last} of {totalRecords}"
                               globalFilter={this.state.globalFilter}
                               header={header}>

                        <Column selectionMode="multiple" headerStyle={{width: '3rem'}}></Column>
                        <Column field="id" header="id" sortable></Column>
                        <Column field="codigo" header="Codigo" sortable></Column>
                        <Column field="nome" header="Nome" sortable></Column>
                        <Column field="eletiva" header="Eletiva" sortable></Column>
                        <Column field="pos" header="Pos" sortable></Column>
                        <Column body={this.actionBodyTemplate}></Column>
                    </DataTable>
                </div>

                <Dialog visible={this.state.disciplinaDialog} style={{width: '450px'}} header="disciplina Details"
                        modal className="p-fluid" footer={disciplinaDialogFooter} onHide={this.hideDialog}>
                    <div className="p-field">
                        <label htmlFor="nome">Nome</label>
                        <InputText id="nome" value={this.state.disciplina.nome}
                                   onChange={(e) => this.onInputChange(e, 'nome')} required autoFocus
                                   className={classNames({'p-invalid': this.state.submitted && !this.state.disciplina.nome})}/>
                        {this.state.submitted && !this.state.disciplina.nome &&
                        <small className="p-invalid">nome is required.</small>}
                    </div>
                    <div className="p-field">
                        <label htmlFor="codigo">Codigo</label>
                        <InputText id="codigo" value={this.state.disciplina.codigo}
                                   onChange={(e) => this.onInputChange(e, 'codigo')} required rows={3} cols={20}/>
                    </div>
                    <div className="p-field">
                        <label htmlFor="eletiva">Eletiva</label>
                        <InputText id="eletiva" value={this.state.disciplina.eletiva}
                                   onChange={(e) => this.onInputChange(e, 'eletiva')} required rows={3} cols={20}/>
                    </div>
                    <div className="p-field">
                        <label htmlFor="pos">Pos</label>
                        <InputText id="pos" value={this.state.disciplina.pos}
                                   onChange={(e) => this.onInputChange(e, 'pos')} required rows={3} cols={20}/>
                    </div>
                </Dialog>


                <Dialog visible={this.state.disciplinaEditDialog} style={{width: '450px'}} header="disciplina Edit"
                        modal className="p-fluid" footer={disciplinaDialogFooterUpdate} onHide={this.hideDialog}>
                    <div className="p-field">
                        <label htmlFor="id">ID</label>
                        <InputText id="id" value={this.state.disciplina._id} disabled="true"
                                   onChange={(e) => this.onInputChange(e, 'id')} required autoFocus
                                   className={classNames({'p-invalid': this.state.submitted && !this.state.disciplina._id})}/>

                        <label htmlFor="nome">Nome</label>
                        <InputText id="nome" value={this.state.disciplina.nome}
                                   onChange={(e) => this.onInputChange(e, 'nome')} required autoFocus
                                   className={classNames({'p-invalid': this.state.submitted && !this.state.disciplina.nome})}/>
                        {this.state.submitted && !this.state.disciplina.nome &&
                        <small className="p-invalid">nome is required.</small>}
                    </div>
                    <div className="p-field">
                        <label htmlFor="codigo">Codigo</label>
                        <InputText id="codigo" value={this.state.disciplina.codigo}
                                   onChange={(e) => this.onInputChange(e, 'codigo')} required rows={3} cols={20}/>
                    </div>
                    <div className="p-field">
                        <label htmlFor="eletiva">Eletiva</label>
                        <InputText id="eletiva" value={this.state.disciplina.eletiva}
                                   onChange={(e) => this.onInputChange(e, 'eletiva')} required rows={3} cols={20}/>
                    </div>
                    <div className="p-field">
                        <label htmlFor="pos">Pos</label>
                        <InputText id="pos" value={this.state.disciplina.pos}
                                   onChange={(e) => this.onInputChange(e, 'pos')} required rows={3} cols={20}/>
                    </div>
                </Dialog>


                <Dialog visible={this.state.deleteDisciplinaDialog} style={{width: '450px'}} header="Confirm" modal
                        footer={deleteDisciplinaDialogFooter} onHide={this.hideDeleteDisciplinaDialog}>
                    <div className="confirmation-content">
                        <i className="pi pi-exclamation-triangle p-mr-3" style={{fontSize: '2rem'}}/>
                        {this.state.disciplina &&
                        <span>Are you sure you want to delete <b>{this.state.disciplina.nome}</b>?</span>}
                    </div>
                </Dialog>

                <Dialog visible={this.state.deleteDisciplinasDialog} style={{width: '450px'}} header="Confirm" modal
                        footer={deleteDisciplinasDialogFooter} onHide={this.hideDeleteDisciplinasDialog}>
                    <div className="confirmation-content">
                        <i className="pi pi-exclamation-triangle p-mr-3" style={{fontSize: '2rem'}}/>
                        {this.state.disciplina &&
                        <span>Are you sure you want to delete the selected products?</span>}
                    </div>
                </Dialog>
            </div>
        );
    }
}



Post Reply

Return to “PrimeReact”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 1 guest