Have you ever needed to create a custom form based on a SharePoint list? This article is for you!
With the @pnp/spfx-controls-react
NPM package you can quickly create a form based on the fields of a SharePoint list.
To use the DynamicForm
control you have to create an SPFx solution, you can use Yeoman with the @microsoft/sharepoint
generator, and after that install the package using:
npm i @pnp/spfx-controls-react
Once you have the package installed you have to import the DynamicForm
adding the following code in the in control class:
import { DynamicForm } from "@pnp/spfx-controls-react/lib/DynamicForm";
Now you have to add the DynamicForm
control inside the render
method:
<DynamicForm
context={this.props.context as any}
listId={"here-goes-your-list-guid"}
/>
NB: In the listId
property you have to specify the GUID of the target SharePoint list.
By now you should be wondering what the property context
in the control properties is and to answer that you should know that the DynamicForm uses the context of the web part so you have to add the WebPartContext property to the control properties interface. To do so you have to import the property type definition:
import { WebPartContext } from "@microsoft/sp-webpart-base";
And then define the property:
context: WebPartContext;
Then in the web part class, inside the render
method, you have to pass the this.context
property to the control class:
public render(): void {
const element: React.ReactElement<IBasicDynamicFormProps> = React.createElement(
BasicDynamicForm,
{
context: this.context
}
);
ReactDom.render(element, this.domElement);
}
And now you’re ready to test your new form!
Execute the serve command:
gulp serve --nobrowser
Open the workbench page in the site of your target list, add your web part and here you have your form!
With the current definition of the control you can only add new items to the list, but if you specify the listItemId
property then you can edit the item with the specified ID.
I created a sample list with various type of fields to show you how the form display:
You can find the documentation of the DynamicForm control here, if you want to check the code that I used for this article you can find it here.
Hope that helps!
Top comments (0)