...
Create Form UI:-
First, we will need to create a form where users can enter all required information and submit the form.
for that, we need to create an index.js into web->micor-ui->internals ->packages->module->br->src->pages->citizen->create(you can give any name instead of create)->index.js
In Index.js will import the Formcomposer that is already present. inside that, we will add Heading, label, and config.
Code Block |
---|
import { FormComposer } from "@egovernments/digit-ui-react-components"; import React from "react"; import { useTranslation } from "react-i18next"; import { newConfig } from "../../../components/config/config"; const Create = () => { const { t } = useTranslation(); const configs = newConfig?newConfig:newConfig; return ( <FormComposer heading={t("Create Birth Registration")} label={t("ES_COMMON_APPLICATION_SUBMIT")} config={configs.map((config) => { return { ...config, body: config.body.filter((a) => !a.hideInEmployee), }; })} fieldStyle={{ marginRight: 0 }} /> ); }; export default Create; |
...
Config.js:-
In Config.js we create a JSON file where it contains the head that is the header heading of our form then in the body, we are adding type so in type we mention the component and we add the component name e.g:- We create BrSelectName.js inside that we maintain the form label, details, and validation. so like that same for other fields also we create. once newConfig components are added then will map newConfig Json in the above index.js so the fields should be rendered to UI.
Code Block |
---|
export const newConfig =[ { "head": "Birth-Details", "body": [ { type: "component", component: "BrSelectName", key: "BrSelectName", withoutLabel: true, }, { type: "component", component: "BRSelectGender", key: "BRSelectPhoneGender", withoutLabel: true, }, { type: "component", component: "BRSelectPhoneNumber", key: "BRSelectPhoneNumber", withoutLabel: true, }, { type: "component", component: "BRSelectEmailId", key: "BRSelectEmailId", withoutLabel: true, }, { type: "component", component: "BrSelectAddress", key: "BrSelectAddress", withoutLabel: true, }, { type: "component", component: "SelectCorrespondenceAddress", key: "SelectCorrespondenceAddress", withoutLabel: true, }, ] }, ]; |
...
Code Block |
---|
import { AppContainer, BackButton,PrivateRoute } from "@egovernments/digit-ui-react-components"; import React from "react"; import { Switch, useRouteMatch } from "react-router-dom"; import { useTranslation } from "react-i18next"; const App = () => { const { path, url, ...match } = useRouteMatch(); const { t } = useTranslation(); const Create = Digit?.ComponentRegistryService?.getComponent("BRCreate"); const Response = Digit?.ComponentRegistryService?.getComponent("Response"); return ( <span className={"pt-citizen"}> <Switch> <AppContainer> <BackButton>Back</BackButton> <PrivateRoute path={`${path}/birth`} component={Create} /> <PrivateRoute path={`${path}/response`} component={Response} /> </AppContainer> </Switch> </span> ); }; export default App; |
...
Add Card On Homepage:-
once the form is created and also routing is added we add the Birth-Registration Module card on our DIgit-UI Homepage.
Module.js:-
Module.js is the entry point of every module e.g:- ( Birth-Registration, Property Tax ) so here we need to Register all the components, Links, Module Codes, etc.
Code Block |
---|
import { CitizenHomeCard, PTIcon } from "@egovernments/digit-ui-react-components"; import React, { useEffect } from "react"; import { useTranslation } from "react-i18next"; import { useRouteMatch } from "react-router-dom"; import CitizenApp from "./pages/citizen"; import Create from "./pages/citizen/create/index"; import EmployeeApp from "./pages/employee"; import BrSelectName from "./pagecomponents/BrSelectName"; import BRSelectPhoneNumber from "./pagecomponents/BrSelectPhoneNumber"; import BRSelectGender from "./pagecomponents/BRSelectGender"; import BRSelectEmailId from "./pagecomponents/SelectEmailId"; import BRSelectPincode from "./pagecomponents/BRSelectPincode"; import BrSelectAddress from "./pagecomponents/BrSelectAddress"; import SelectCorrespondenceAddress from "./pagecomponents/SelectCorrespondenceAddress"; import SelectDocuments from "./pagecomponents/SelectDocuments"; import BRCard from "./components/config/BRCard"; import BRManageApplication from "./pages/employee/BRManageApplication"; import RegisterDetails from "./pages/employee/RegisterDetails"; import Response from "./pages/citizen/create/Response"; const componentsToRegister = { Response, RegisterDetails, BRManageApplication, BRCard, SelectDocuments, SelectCorrespondenceAddress, BrSelectAddress, BRSelectPincode, BRSelectEmailId, BRSelectGender, BRSelectPhoneNumber, BrSelectName, BRCreate : Create, }; export const BRModule = ({ stateCode, userType, tenants }) => { const { path, url } = useRouteMatch(); const moduleCode = "BR"; const language = Digit.StoreData.getCurrentLanguage(); const { isLoading, data: store } = Digit.Services.useStore({ stateCode, moduleCode, language }); if (userType === "citizen") { return <CitizenApp path={path} stateCode={stateCode} />; } return <EmployeeApp path={path} stateCode={stateCode} />; }; export const BRLinks = ({ matchPath, userType }) => { const { t } = useTranslation(); const links = [ { link: `${matchPath}/birth`, i18nKey: t("Create BirthRegistration"), }, ]; return <CitizenHomeCard header={t("BirthRegistration")} links={links} Icon={() => <PTIcon className="fill-path-primary-main" />} />; }; export const initBRComponents = () => { Object.entries(componentsToRegister).forEach(([key, value]) => { Digit.ComponentRegistryService.setComponent(key, value); }); }; |
...
Enable Module:-
After Register all components, Links, and module code we need to enable it in Two Places:-
1) Web-> Src->app.js :-
In app.js we import the BRModule, initBRComponents, and BRLinks and enable the BR module.
Code Block |
---|
import React from 'react'; import { initDSSComponents } from "@egovernments/digit-ui-module-dss"; import { PaymentModule, PaymentLinks, paymentConfigs } from "@egovernments/digit-ui-module-common"; import { DigitUI } from "@egovernments/digit-ui-module-core"; import { initLibraries } from "@egovernments/digit-ui-libraries"; import { initEngagementComponents } from "@egovernments/digit-ui-module-engagement"; // import { initWSComponents } from "@egovernments/digit-ui-module-ws"; import {initCustomisationComponents} from "./Customisations"; import { initCommonPTComponents } from "@egovernments/digit-ui-module-commonpt"; import { BRModule ,initBRComponents ,BRLinks} from "@egovernments/digit-ui-module-br"; initLibraries(); //"WS" removed the ws enabledModules ; const enabledModules = ["Payment","QuickPayLinks", "DSS","Engagement", "BR"]; window.Digit.ComponentRegistryService.setupRegistry({ ...paymentConfigs, PaymentModule, PaymentLinks, BRModule, BRLinks, }); initBRComponents(); initDSSComponents(); initEngagementComponents(); // initWSComponents(); initCustomisationComponents(); function App() { const stateCode = window.globalConfigs?.getConfig("STATE_LEVEL_TENANT_ID") || process.env.REACT_APP_STATE_LEVEL_TENANT_ID; if (!stateCode) { return <h1>stateCode is not defined</h1> } return ( <DigitUI stateCode={stateCode} enabledModules={enabledModules} /> ); } export default App; |
...
Code Block |
---|
import React from "react"; import ReactDOM from "react-dom"; import { initLibraries } from "@egovernments/digit-ui-libraries"; import { BRModule, initBRComponents ,BRLinks} from "@egovernments/digit-ui-module-br"; import { initDSSComponents } from "@egovernments/digit-ui-module-dss"; import { PaymentModule, PaymentLinks, paymentConfigs } from "@egovernments/digit-ui-module-common"; import { initEngagementComponents } from "@egovernments/digit-ui-module-engagement"; import { DigitUI } from "@egovernments/digit-ui-module-core"; import "@egovernments/digit-ui-css// import {initCustomisationComponents} from "./customisations"; // import { PGRModule, PGRLinks } from "@egovernments/digit-ui-module-pgr"; // import { Body, TopBar } from "@egovernments/digit-ui-react-components"; import "@egovernments/digit-ui-css/example/index.css"; // import * as comps from "@egovernments/digit-ui-react-components"; // import { subFormRegistry } from "@egovernments/digit-ui-libraries"; var Digit = window.Digit || {}; const enabledModules = [ "Payment","QuickPayLinks", "DSS","Engagement","BR"]; const initTokens = (stateCode) => { const userType = window.sessionStorage.getItem("userType") || process.env.REACT_APP_USER_TYPE || "CITIZEN"; const token =window.localStorage.getItem("token")|| process.env[`REACT_APP_${userType}_TOKEN`]; const citizenInfo = window.localStorage.getItem("Citizen.user-info") const citizenTenantId = window.localStorage.getItem("Citizen.tenant-id") || stateCode; const employeeInfo = window.localStorage.getItem("Employee.user-info"); const employeeTenantId = window.localStorage.getItem("Employee.tenant-id"); const userTypeInfo = userType === "CITIZEN" || userType === "QACT" ? "citizen" : "employee";example/index.css"; var Digit = window.Digit || {}; const enabledModules = [ "Payment","QuickPayLinks", "DSS","Engagement","BR"]; const initTokens = (stateCode) => { const userType = window.sessionStorage.getItem("userType") || process.env.REACT_APP_USER_TYPE || "CITIZEN"; const token =window.localStorage.getItem("token")|| process.env[`REACT_APP_${userType}_TOKEN`]; const citizenInfo = window.localStorage.getItem("Citizen.user-info") const citizenTenantId = window.localStorage.getItem("Citizen.tenant-id") || stateCode; const employeeInfo = window.localStorage.getItem("Employee.user-info"); const employeeTenantId = window.localStorage.getItem("Employee.tenant-id"); const userTypeInfo = userType === "CITIZEN" || userType === "QACT" ? "citizen" : "employee"; window.Digit.SessionStorage.set("user_type", userTypeInfo); window.Digit.SessionStorage.set("userType", userTypeInfo); if (userType !== "CITIZEN") { window.Digit.SessionStorage.set("user_typeUser", userTypeInfo); window.Digit.SessionStorage.set("userType", userTypeInfo); if (userType !== "CITIZEN") { window.Digit.SessionStorage.set("User", { access_token: token, { access_token: token, info: userType !== "CITIZEN" ? JSON.parse(employeeInfo) : citizenInfo }); } else { // if (!window.Digit.SessionStorage.get("User")?.extraRoleInfo) window.Digit.SessionStorage.set("User", { access_token: token, info: citizenInfo }); } window.Digit.SessionStorage.set("Citizen.tenantId", citizenTenantId); if(employeeTenantId && employeeTenantId.length) window.Digit.SessionStorage.set("Employee.tenantId", employeeTenantId); }; const initDigitUI = () => { window?.Digit.ComponentRegistryService.setupRegistry({ PaymentModule, BRModule, PaymentLinks, BRLinks, }); initDSSComponents(); initEngagementComponents(); initBRComponents(); // TLModule, // TLLinks, const stateCode }); initDSSComponents(); initEngagementComponents(); initBRComponents(); // initCustomisationComponents(); const stateCode = = window?.globalConfigs?.getConfig("STATE_LEVEL_TENANT_ID") || "pb"; initTokens(stateCode); const registry = window?.Digit.ComponentRegistryService.getRegistry(); ReactDOM.render(<DigitUI stateCode={stateCode} enabledModules={enabledModules} />, document.getElementById("root")); }; initLibraries().then(() => { initDigitUI(); }); |
...
Integration with Backend API:-Hooks: -
Code Block |
---|
import { useQuery, useMutation } from "react-query";
import BRService from "../../services/elements/BR";
export const useBRCreate = (tenantId, config = {}) => {
return useMutation((data) => BRService.create(data, tenantId));
};
export default useBRCreate;
|
service → elements
...
we have done with the UI part for the citizen module, now we will see how to integrate it with the backend API.
Service:-
we create a service where we mention the API's call e.g:- POST, GET, PUT, PATCH, etc.
basically, we will create a request inside the request we pass the data, URL, method, auth, and other params.
Code Block |
---|
import Urls from "../atoms/urls"; import { Request } from "../atoms/Utils/Request"; const BRService = { create: (data, tenantId) => Request({ data: data, url: Urls.br.create, useCache: false, method: "POST", auth: true, userService: true, params: { tenantId }, }), get: (data, tenantId) => Request({ data: data, url: Urls.br.get, useCache: false, method: "GET", auth: true, userService: true, params: { tenantId }, useCache: false}), method: "GET", }; export default auth: true,BRService; |
In Request, we are passing the URL so that url we mention or add into the service-> atoms-> url.js
Code Block |
---|
br: { create: userService: true"https://62f0e3e5e2bca93cd23f2ada.mockapi.io/user", params: { tenantId },get:"https://62f0e3e5e2bca93cd23f2ada.mockapi.io/user", }), }; export default BRService; |
service-> atoms-> url.js
Code Block |
---|
br: {
create: "https://62f0e3e5e2bca93cd23f2ada.mockapi.io/user",
get:"https://62f0e3e5e2bca93cd23f2ada.mockapi.io/user",
}, |
...
Code Block |
---|
, |
Hooks: -
Once BRService is created with all requests then will create a Hook and that hook we will use in our code to pass the data to the backend.
Code Block |
---|
import { useQuery, useMutation } from "react-query";
import BRService from "../../services/elements/BR";
export const useBRCreate = (tenantId, config = {}) => {
return useMutation((data) => BRService.create(data, tenantId));
};
export default useBRCreate;
|
After creating Service and Hooks we need to register it into packages-> libraries->src->index.js
Code Block |
---|
import Enums from "./enums/index"; import mergeConfig from "./config/mergeConfig"; import { useStore } from "./services/index"; import { initI18n } from "./translations/index"; import { Storage, PersistantStorage } from "./services/atoms/Utils/Storage"; import { UserService } from "./services/elements/User"; import { ULBService } from "./services/molecules/Ulb"; import Hooks from "./hooks"; import { subFormRegistry } from "./subFormRegistry"; import BRService from "./services/elements/BR"; const setupLibraries = (Library, props) => { window.Digit = window.Digit || {}; window.Digit[Library] = window.Digit[Library] || {}; window.Digit[Library] = { ...window.Digit[Library], ...props }; }; const initLibraries = () => { setupLibraries("SessionStorage", Storage); setupLibraries("PersistantStorage", PersistantStorage); setupLibraries("UserService", UserService); setupLibraries("ULBService", ULBService); setupLibraries("Config", { mergeConfig }); setupLibraries("Services", { useStore }); setupLibraries("BRService", BRService); return new Promise((resolve) => { initI18n(resolve); }); }; export { initLibraries, Enums, Hooks, subFormRegistry }; |
Use service into create.js add-on submit function so we setup the backend service, and now we will use the hooks or service to send the data backend. after submitting the form.
so we add the onSubmit function in our code (br->src->pages->citizen->create->index.js) and in that function, we are passing the user’s entered data to the BRService that we have created.
Code Block |
---|
import { FormComposer, Loader } from "@egovernments/digit-ui-react-components";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { newConfig } from "../../../components/config/config";
const Create = () => {
const tenantId = Digit.ULBService.getCurrentTenantId();
const { t } = useTranslation();
const history = useHistory();
const onSubmit = (data) => {
let Users = [
{
user: {
babyFirstName: data?.BrSelectName?.babyFirstName,
babyLastName: data?.BrSelectName?.babyLastName,
fatherName: data?.BrSelectName?.fatherName,
motherName: data?.BrSelectName?.motherName,
gender: data?.BrSelectGender?.gender,
doctorName: data?.BrSelectName?.doctorName,
hospitalName: data?.BrSelectName?.hospitalName,
placeOfBirth: data?.BrSelectName?.placeOfBirth,
applicantMobileNumber: data?.BRSelectPhoneNumber?.applicantMobileNumber,
altMobileNumber: data?.BRSelectPhoneNumber?.altMobileNumber,
emailId: data?.BRSelectEmailId?.emailId,
permanentAddress: data?.BrSelectAddress?.permanentAddress,
permanentCity: data?.BrSelectAddress?.permanentCity,
correspondenceCity: data?.SelectCorrespondenceAddress?.correspondenceCity,
correspondenceAddress: data?.SelectCorrespondenceAddress?.correspondenceAddress,
bloodGroup: data?.SelectCorrespondenceAddress?.bloodGroup,
tenantId: tenantId,
},
},
];
/* use customiseCreateFormData hook to make some chnages to the Employee object */
Digit.BRService.create(Users, tenantId).then((result,err)=>{
let getdata = {...data , get: result }
onSelect("", getdata, "", true);
console.log("daaaa",getdata);
})
.catch((e) => {
console.log("err");
});
history.push("/digit-ui/citizen/br/response");
console.log("getting data",Users)
};
/* use newConfig instead of commonFields for local development in case needed */
const configs = newConfig?newConfig:newConfig;
return (
<FormComposer
heading={t("Create Birth Registration")}
label={t("ES_COMMON_APPLICATION_SUBMIT")}
config={configs.map((config) => {
return {
...config,
body: config.body.filter((a) => !a.hideInEmployee),
};
})}
onSubmit={onSubmit}
fieldStyle={{ marginRight: 0 }}
/>
);
};
export default Create;
|
your integration is done your data will save into the database.