Microsoft forms Api

MOD Administrator 0 Reputation points
2023-08-23T15:11:19.3366667+00:00

Bonjour,

je suis entrain de mettre en place une application SharePoint spfx react Framework, qui récupère l'ensemble des formulaires de Microsoft forms d'un compte spécifique de Microsoft. capable aussi de récupérer une question spécifique et la réponse d'un user spécifique via une API.

cordialement.

Romeo Leuwat

Microsoft 365 and Office SharePoint For business Windows
Microsoft Security Microsoft Graph
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-08-24T05:51:25.15+00:00

    Hi @MOD Administrator,

    I tried to use spfx react to add, delete, modify and check a list, here is a template for your reference:

    User's image

    User's image

    These codes are only applicable to my scenario (the code is for reference only, and the specific parameters need to be set by yourself), and you need to adjust it according to your scenario

    import * as React from 'react';
    import { IHelloWorldProps } from './IHelloWorldProps';
    //import { escape } from '@microsoft/sp-lodash-subset';
    import styles from './HelloWorld.module.scss';
    import { DatePicker, IDatePickerStrings } from 'office-ui-fabric-react/lib/DatePicker';
    import { PeoplePicker, PrincipalType } from "@pnp/spfx-controls-react/lib/PeoplePicker";
    import { TextField } from 'office-ui-fabric-react/lib/TextField';
    import { Label } from 'office-ui-fabric-react/lib/Label';
    import { Web } from "@pnp/sp/presets/all";
    import "@pnp/sp/lists";
    import "@pnp/sp/items";
    import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
    import { VerticalDivider } from 'office-ui-fabric-react/lib/Divider';
    import { ChoiceGroup, IChoiceGroupOption } from '@fluentui/react';
    
    
    
    
    export interface IStates {
        Items: any;
        ID: any;
        EmployeeName: any;
        EmployeeNameId: any;
        HireDate: Date;
        JobDescription: any;
        HTML: any;
        //singleValueChoiceGroup: string;
        multiValueCheckbox: any;
        singleValueOptions: any;
        multiValueOptions: any;
        Test: any;
        Choices: [];
    }
    
    
    
    export default class CRUDReact extends React.Component<IHelloWorldProps, IStates> {
        constructor(props: IHelloWorldProps | Readonly<IHelloWorldProps>) {
            super(props);
            this.state = {
                Items: [],
                EmployeeName: "",
                EmployeeNameId: 0,
                ID: 0,
                HireDate: null,
                JobDescription: "",
                HTML: [],
                //singleValueChoiceGroup: "",
                multiValueCheckbox: [],
                singleValueOptions: [],
                multiValueOptions: [],
                Test: "",
                Choices: []
    
            };
            this.onchange = this.onchange.bind(this);
        }
    
        public async componentDidMount() {
            await this.fetchData();
            var singleValue = await this.getCheckboxChoices("Test");
            this.setState({ singleValueOptions: singleValue });
        }
    
        public async fetchData() {
            console.log('fetchData');
    
            let web = Web(this.props.webURL);
            const items: any[] = await web.lists.getByTitle("EmployeeDetails").items.select("*", "EmployeeName/Title").expand("EmployeeName/ID").get();
            console.log(items);
            this.setState({ Items: items });
            let html = await this.getHTML(items);
            this.setState({ HTML: html });
    
        }
      
        public findData = (id: any): void => {
            //this.fetchData();
            var itemID = id;
            var allitems = this.state.Items;
            var allitemsLength = allitems.length;
            if (allitemsLength > 0) {
                for (var i = 0; i < allitemsLength; i++) {
                    if (itemID == allitems[i].Id) {
                        this.setState({
                            ID: itemID,
                            EmployeeName: allitems[i].EmployeeName.Title,
                            EmployeeNameId: allitems[i].EmployeeNameId,
                            HireDate: new Date(allitems[i].HireDate),
                            JobDescription: allitems[i].JobDescription,
                            Test: allitems[i].Test
                        });
                    }
                }
            }
            console.log(allitems)
            console.log('findfate');
    
        }
    
        public async getHTML(items: any[]) {
            var tabledata = <table >
                <thead>
                    <tr>
                        <th>Employee Name</th>
                        <th>Hire Date</th>
                        <th>Job Description</th>
                        <th>Test</th>
                    </tr>
                </thead>
                <tbody>
                    {items && items.map((item, i) => {
                        return [
                            <tr key={i} onClick={() => this.findData(item.ID)}>
                                <td>{item.EmployeeName.Title}</td>
                                <td>{item.HireDate}</td>
                                <td>{item.JobDescription}</td>
                                <td>{item.Test}</td>
                            </tr>
                        ];
                    })}
                </tbody>
    
            </table>;
            return await tabledata;
        }
        public _getPeoplePickerItems = async (items: any[]) => {
    
            if (items.length > 0) {
    
                this.setState({ EmployeeName: items[0].text });
                this.setState({ EmployeeNameId: items[0].id });
            }
            else {
                //ID=0;
                this.setState({ EmployeeNameId: "" });
                this.setState({ EmployeeName: "" });
            }
            console.log(items)
        }
        public onchange(event: React.ChangeEvent<HTMLInputElement>) {
    
            this.setState({ JobDescription: event.target.value });
    
        }
        public async getCheckboxChoices(fieldname: string) {
    
            var singlevaluechoices: { key: any; text: any; }[] = [];
            let web = Web(this.props.webURL);
            await web.lists.getByTitle("EmployeeDetails").fields.getByInternalNameOrTitle(fieldname).select('Choices').get().then((field) => {
                console.log(field);
                for (var i = 0; i < (field as any)["Choices"].length; i++) {
                    singlevaluechoices.push({
                        key: (field as any)["Choices"][i],
                        text: (field as any)["Choices"][i]
                    });
                }
    
            });
            return singlevaluechoices;
        }
    
    
        public _onChange = async (ev: React.FormEvent<HTMLInputElement>, option: IChoiceGroupOption): Promise<void> => {
            console.log(option);
            this.setState({ Test: option.key });
        }
    
    
    
        private async SaveData() {
            // console.log(this.state.EmployeeNameId);
            console.log(this.state);
    
            let web = Web(this.props.webURL);
    
    
            await web.lists.getByTitle("EmployeeDetails").items.add({
    
                EmployeeNameId: this.state.EmployeeNameId,
                HireDate: this.state.HireDate,
                JobDescription: this.state.JobDescription,
                Test: this.state.Test
    
            });
            console.log(this.state);
            alert("Created Successfully");
            this.setState({ EmployeeName: "", HireDate: null, JobDescription: "" });
            this.fetchData();
        }
        private async UpdateData() {
            console.log('testaction');
            let web = Web(this.props.webURL);
            await web.lists.getByTitle("EmployeeDetails").items.getById(this.state.ID).update({
    
                EmployeeNameId: this.state.EmployeeNameId,
                HireDate: this.state.HireDate,
                JobDescription: this.state.JobDescription,
                Test: this.state.Test
    
            });
            console.log(this.state);
            alert("Updated Successfully");
            this.setState({ EmployeeName: "", HireDate: null, JobDescription: "" });
            this.fetchData();
        }
        private async DeleteData() {
    
    
            let web = Web(this.props.webURL);
            await web.lists.getByTitle("EmployeeDetails").items.getById(this.state.ID).delete();
    
            alert("Deleted Successfully");
            this.setState({ EmployeeName: "", HireDate: null, JobDescription: "" });
            this.fetchData();
        }
    
        public render(): React.ReactElement<IHelloWorldProps> {
            return (
                <div>
                    <h1>CRUD Operations With ReactJs</h1>
                    {this.state.HTML}
    
                    <div>
                        <form>
                            <div>
                                <Label>Employee Name</Label>
                                <PeoplePicker
                                    context={this.props.context}
                                    personSelectionLimit={1}
                                    // defaultSelectedUsers={this.state.EmployeeName===""?[]:this.state.EmployeeName}
                                    required={false}
                                    onChange={this._getPeoplePickerItems}
                                    defaultSelectedUsers={[this.state.EmployeeName ? this.state.EmployeeName : ""]}
                                    showHiddenInUI={false}
                                    principalTypes={[PrincipalType.User]}
                                    resolveDelay={1000}
                                    ensureUser={true}
                                />
                            </div>
                            <VerticalDivider></VerticalDivider>
                            <div>
                                <Label>Hire Date</Label>
                                <DatePicker allowTextInput={false} strings={DatePickerStrings} value={this.state.HireDate} onSelectDate={(e) => { this.setState({ HireDate: e }); }} ariaLabel="Select a date" formatDate={FormatDate} />
                            </div>
                            <div>
                                <Label>Job Description</Label>
                                <TextField value={this.state.JobDescription} multiline onChange={this.onchange} />
                            </div>
                            <div>
                                <Label>Single Select ChoiceGroup</Label>
                                <ChoiceGroup onChange={this._onChange} options={this.state.singleValueOptions} selectedKey={this.state.Test} />
                            </div>
    
                        </form>
                    </div>
                    <div className={styles.btngroup}>
                        <div><PrimaryButton text="Create" onClick={() => this.SaveData()} /></div>
                        <div><PrimaryButton text="Update" onClick={() => this.UpdateData()} /></div>
                        <div><PrimaryButton text="Delete" onClick={() => this.DeleteData()} /></div>
                    </div>
                </div>
            );
        }
    }
    export const DatePickerStrings: IDatePickerStrings = {
        months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        shortDays: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
        goToToday: 'Go to today',
        prevMonthAriaLabel: 'Go to previous month',
        nextMonthAriaLabel: 'Go to next month',
        prevYearAriaLabel: 'Go to previous year',
        nextYearAriaLabel: 'Go to next year',
        invalidInputErrorMessage: 'Invalid date format.'
    };
    export const FormatDate = (date: Date): string => {
        console.log(date);
        //var date = new Date();
        var date1 = new Date(date.getTime());
        var year = date1.getFullYear();
        var month = (1 + date1.getMonth()).toString();
        month = month.length > 1 ? month : '0' + month;
        var day = date1.getDate().toString();
        day = day.length > 1 ? day : '0' + day;
        return month + '/' + day + '/' + year;
    };
    
    
    

    Here are some links for your reference:

    https://www.spguides.com/retrieve-sharepoint-list-items-using-sharepoint-framework/

    https://global-sharepoint.com/sharepoint/crud-operation-in-sharepoint-online/

    https://www.spguides.com/sharepoint-framework-crud-operations-using-react/


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards

    Cheng Feng


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.