Skip to content

Commit

Permalink
Merge pull request #647 from AkshataKatwal16/reassign-cohorts
Browse files Browse the repository at this point in the history
Issue #PS-3578 feat: combine fl and lastname pass it to username...create custom widget for suggestion list of username after onblur(end user complete his username typing on UI)
  • Loading branch information
itsvick authored Jan 28, 2025
2 parents c262be9 + 2f07864 commit f5c0f09
Show file tree
Hide file tree
Showing 4 changed files with 181 additions and 63 deletions.
83 changes: 42 additions & 41 deletions src/components/AddLeanerModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ interface AddLearnerModalProps {
onReload?: (() => void) | undefined;
learnerEmailId?: string;
learnerUserName?: string;

}
const AddLearnerModal: React.FC<AddLearnerModalProps> = ({
open,
Expand All @@ -50,7 +49,7 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({
userId,
onReload,
learnerUserName,
learnerEmailId
learnerEmailId,
}) => {
const [schema, setSchema] = React.useState<any>();
const [uiSchema, setUiSchema] = React.useState<any>();
Expand Down Expand Up @@ -111,21 +110,17 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({
data: IChangeEvent<any, RJSFSchema, any>,
event: React.FormEvent<any>
) => {
if(data?.formData?.name)
{
data.formData.name = data?.formData?.name?.trim()
if (data?.formData?.name) {
data.formData.name = data?.formData?.name?.trim();
}
if(data?.formData?.father_name)
{
data.formData.father_name = data?.formData?.father_name?.trim()
if (data?.formData?.father_name) {
data.formData.father_name = data?.formData?.father_name?.trim();
}
setTimeout(() => {
setLearnerFormData(data.formData);
});


const formData = data.formData;

};

useEffect(() => {
Expand Down Expand Up @@ -202,7 +197,6 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({
fieldId: fieldData?.state?.districtId,
value: [fieldData?.state?.districtCode],
});

}

try {
Expand All @@ -213,25 +207,22 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({
father_name: apiBody.father_name,
username: apiBody.username,
email: apiBody?.email,
firstName:apiBody?.firstName,
middleName:apiBody?.middleName,
lastName:apiBody?.lastName,
dob:apiBody?.dob,
gender:apiBody?.gender
firstName: apiBody?.firstName,
middleName: apiBody?.middleName,
lastName: apiBody?.lastName,
dob: apiBody?.dob,
gender: apiBody?.gender,
};
const customFields = apiBody.customFields;
const object = {
userData: userData,
customFields: customFields,
};

if(learnerEmailId===userData.email)
{
if (learnerEmailId === userData.email) {
delete userData.email;

}
if(learnerUserName===userData.username)
delete userData.username;
if (learnerUserName === userData.username) delete userData.username;
const response = await editEditUser(userId, object);
if (response) {
showToastMessage(
Expand All @@ -243,8 +234,7 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({
onClose();
}
} else {
if(apiBody?.phone_number)
{
if (apiBody?.phone_number) {
apiBody.mobile = apiBody?.phone_number;
}
const response = await createUser(apiBody);
Expand Down Expand Up @@ -291,11 +281,12 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({
}
}
} catch (error: any) {
if (error?.response?.data?.params?.err === "User already exist.") {
showToastMessage(error?.response?.data?.params?.err, "error");
}
else if (error?.response?.data?.params?.errmsg === "Email already exists") {
showToastMessage(error?.response?.data?.params?.errmsg, "error");
if (error?.response?.data?.params?.err === 'User already exist.') {
showToastMessage(error?.response?.data?.params?.err, 'error');
} else if (
error?.response?.data?.params?.errmsg === 'Email already exists'
) {
showToastMessage(error?.response?.data?.params?.errmsg, 'error');
} else {
showToastMessage(t('COMMON.SOMETHING_WENT_WRONG'), 'error');
}
Expand All @@ -307,22 +298,31 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({
}
};


const handleChange = (event: IChangeEvent<any>) => {
// if (!isEditModal) {
// const { firstName, lastName } = event.formData;

// if (firstName && lastName) {
// event.formData.username = firstName + lastName;
// } else {
// event.formData.username = "";
// }
// setCustomFormData({ ...event.formData });
const { formData } = event;

// }

if (!isEditModal) {
const { firstName, lastName, username } = formData;
if (firstName && lastName) {
const updatedUsername = event.formData.username
? username
: firstName && lastName
? (firstName + lastName).toLowerCase()
: '';

const updatedFormData = {
...formData,
username: updatedUsername,
};

setCustomFormData(updatedFormData);
} else {
setCustomFormData({ ...event.formData });
}
} else {
setCustomFormData({ ...formData });
}
};


const handleError = (errors: any) => {
console.log('Form errors:', errors);
Expand Down Expand Up @@ -371,6 +371,7 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({
showErrorList={true}
customFields={customFields}
formData={customFormData ?? undefined}
setFormData={setCustomFormData}
>
<FormButtons
formData={formData ?? learnerFormData}
Expand Down
69 changes: 53 additions & 16 deletions src/components/DynamicForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,29 @@ import { Theme as MaterialUITheme } from '@rjsf/mui';
import { RJSFSchema, RegistryFieldsType, WidgetProps } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
import { useTranslation } from 'next-i18next';
import React, { ReactNode, useEffect } from 'react';
import React, { ReactNode, useEffect, useState } from 'react';
import CustomRadioWidget from './CustomRadioWidget';
import MultiSelectCheckboxes from './MultiSelectCheckboxes';
import MultiSelectDropdown from './MultiSelectDropdown';
import CustomNumberWidget from './CustomNumberWidget';
import UsernameWithSuggestions from './UsernameWithSuggestions';

const FormWithMaterialUI = withTheme(MaterialUITheme);

interface DynamicFormProps {
schema: any;
uiSchema: object;
formData?: object;
formData?: {
username?: string;
[key: string]: any;
};
onSubmit: (
data: IChangeEvent<any, RJSFSchema, any>,
event: React.FormEvent<any>
) => void | Promise<void>;
onChange: (event: IChangeEvent<any>) => void;
onError: (errors: any) => void;
setFormData?: (data: any) => void;
showErrorList: boolean;

widgets: {
Expand All @@ -43,14 +48,19 @@ const DynamicForm: React.FC<DynamicFormProps> = ({
onError,
customFields,
children,
setFormData,
}) => {
const widgets = {
MultiSelectCheckboxes: MultiSelectCheckboxes,
CustomRadioWidget: CustomRadioWidget,
MultiSelectDropdown: MultiSelectDropdown,
CustomNumberWidget: CustomNumberWidget,
UsernameWithSuggestions: UsernameWithSuggestions as React.FC<
WidgetProps<any, RJSFSchema, any>
>,
};
const { t } = useTranslation();
const [suggestions, setSuggestions] = useState<string[]>([]);

const submittedButtonStatus = useSubmittedButtonStore(
(state: any) => state.submittedButtonStatus
Expand Down Expand Up @@ -83,13 +93,16 @@ const DynamicForm: React.FC<DynamicFormProps> = ({
};
const sanitizeFormData = (data: any): any => {
if (Array.isArray(data)) {
return data.map(item => (typeof item === "undefined" ? '' : sanitizeFormData(item)));
return data.map((item) =>
typeof item === 'undefined' ? '' : sanitizeFormData(item)
);
}
if (data !== null && typeof data === 'object') {
return Object.fromEntries(

Object.entries(data)?.map(([key, value]) => [key, value === "undefined" ? "" : sanitizeFormData(value)])

Object.entries(data)?.map(([key, value]) => [
key,
value === 'undefined' ? '' : sanitizeFormData(value),
])
);
}
return data;
Expand Down Expand Up @@ -186,16 +199,12 @@ const DynamicForm: React.FC<DynamicFormProps> = ({
);
break;
}
case '^[a-zA-Z0-9.@]+$':

{
error.message = t(
'FORM_ERROR_MESSAGES.SPACE_AND_SPECIAL_CHARACTERS_NOT_ALLOWED'
);
break;


}
case '^[a-zA-Z0-9.@]+$': {
error.message = t(
'FORM_ERROR_MESSAGES.SPACE_AND_SPECIAL_CHARACTERS_NOT_ALLOWED'
);
break;
}
default: {
if (error?.property === '.email') {
const validEmail = emailPattern.test(pattern);
Expand Down Expand Up @@ -266,6 +275,25 @@ const DynamicForm: React.FC<DynamicFormProps> = ({
const sanitizedData = sanitizeFormData(event.formData);
onChange({ ...event, formData: sanitizedData });
}
const handleUsernameBlur = async (username: string) => {
if (username) {
try {
console.log('Username onblur called');
// setSuggestions(["1234"])
} catch (error) {
console.error('Error validating username:', error);
}
}
};

const handleSuggestionSelect = (selectedUsername: string) => {
if (setFormData)
setFormData((prev: any) => ({
...prev,
username: selectedUsername,
}));
setSuggestions([]);
};

return (
<div className="form-parent">
Expand All @@ -283,6 +311,15 @@ const DynamicForm: React.FC<DynamicFormProps> = ({
onError={handleError}
transformErrors={transformErrors}
fields={customFields}
formContext={{
suggestions,
onSuggestionSelect: handleSuggestionSelect,
}}
onBlur={(field, value) => {
if (field === 'username') {
handleUsernameBlur(value);
}
}}
>
{children}
</FormWithMaterialUI>
Expand Down
18 changes: 12 additions & 6 deletions src/components/GeneratedSchemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import { UiSchema } from '@rjsf/utils';
import { JSONSchema7 } from 'json-schema';
import NumberInputField from './form/NumberInputField';
import { FormData, Field, FieldOption } from '@/utils/Interfaces';
import { getCurrentYearPattern, getEmailPattern, getLastDayDate } from '@/utils/Helper';
import {
getCurrentYearPattern,
getEmailPattern,
getLastDayDate,
} from '@/utils/Helper';

export const customFields = {
NumberInputField: NumberInputField,
Expand Down Expand Up @@ -57,6 +61,8 @@ export const GenerateSchemaAndUiSchema = (
if (field?.hint) {
fieldUiSchema['ui:help'] = t(`FORM.${field?.hint}`);
}
if (name === 'username')
fieldUiSchema['ui:widget'] = 'UsernameWithSuggestions';

break;
case 'email':
Expand Down Expand Up @@ -115,11 +121,11 @@ export const GenerateSchemaAndUiSchema = (
}));
fieldUiSchema['ui:widget'] = 'CustomRadioWidget';
break;
case 'date':
fieldSchema.type = 'string';
fieldSchema.format = 'date';
fieldUiSchema['ui:widget'] = 'date';
break;
case 'date':
fieldSchema.type = 'string';
fieldSchema.format = 'date';
fieldUiSchema['ui:widget'] = 'date';
break;
default:
break;
}
Expand Down
Loading

0 comments on commit f5c0f09

Please sign in to comment.