draft-js#convertToRaw JavaScript Examples
The following examples show how to use
draft-js#convertToRaw.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WYSIWYG.jsx From saasgear with MIT License | 6 votes |
WYSIWYGEditor = ({ editorContent = '', onChange, className }) => {
const [editorState, setEditorState] = useState(EditorState.createEmpty());
function onEditorStateChange(state) {
setEditorState(state);
return onChange(draftToHtml(convertToRaw(state.getCurrentContent())));
}
useEffect(() => {
if (editorContent === '') {
setEditorState(EditorState.createEmpty());
} else {
const contentState = EditorState.createWithContent(
ContentState.createFromBlockArray(htmlToDraft(editorContent)),
);
setEditorState(contentState);
}
}, [editorContent]);
return (
<Wrapper>
<Editor
editorState={editorState}
wrapperClassName="editor-wrapper"
editorClassName="editor"
toolbarClassName="toolbar"
onEditorStateChange={onEditorStateChange}
/>
</Wrapper>
);
}
Example #2
Source File: exportContent.js From spring-boot-ecommerce with Apache License 2.0 | 6 votes |
MentionGenerator = function () {
function MentionGenerator(contentState, options) {
_classCallCheck(this, MentionGenerator);
this.contentState = contentState;
this.options = options;
}
MentionGenerator.prototype.generate = function generate() {
var contentRaw = convertToRaw(this.contentState);
return this.processContent(contentRaw);
};
MentionGenerator.prototype.processContent = function processContent(contentRaw) {
var blocks = contentRaw.blocks;
var encode = this.options.encode;
return blocks.map(function (block) {
return encode ? encodeContent(block.text) : block.text;
}).join(encode ? '<br />\n' : '\n');
};
return MentionGenerator;
}()
Example #3
Source File: index.jsx From react-antd-admin-template with MIT License | 5 votes |
RichTextEditor = () => {
const [editorState, setEditorState] = useState(EditorState.createEmpty());
const onEditorStateChange = (editorState) => setEditorState(editorState);
return (
<div>
<Card bordered={false}>
<Editor
editorState={editorState}
onEditorStateChange={onEditorStateChange}
wrapperClassName="wrapper-class"
editorClassName="editor-class"
toolbarClassName="toolbar-class"
localization={{ locale: "zh" }}
/>
</Card>
<br />
<Row gutter={10}>
<Col span={12}>
<Card
title="同步转换HTML"
bordered={false}
style={{ minHeight: 200 }}
>
{editorState &&
draftToHtml(convertToRaw(editorState.getCurrentContent()))}
</Card>
</Col>
<Col span={12}>
<Card
title="同步转换MarkDown"
bordered={false}
style={{ minHeight: 200 }}
>
{editorState &&
draftToMarkdown(convertToRaw(editorState.getCurrentContent()))}
</Card>
</Col>
</Row>
</div>
);
}
Example #4
Source File: index.js From discern with BSD 3-Clause "New" or "Revised" License | 5 votes |
render(){
const cardContent = `此页面用到的富文本编辑是<a href="https://github.com/jpuri/react-draft-wysiwyg">react-draft-wysiwyg@^1.12.13</a>`
const { editorState,contentState } = this.state;
return (
<div>
<CustomBreadcrumb arr={['其它','富文本编辑器']}/>
<TypingCard title='富文本编辑器' source={cardContent}/>
<Card bordered={false} className='card-item'>
<Editor
editorState={editorState}
onEditorStateChange={this.onEditorStateChange}
onContentStateChange={this.onContentStateChange}
wrapperClassName="wrapper-class"
editorClassName="editor-class"
toolbarClassName="toolbar-class"
localization={{ locale: 'zh'}}
toolbar={{
image: { uploadCallback: this.uploadImageCallBack, alt: { present: true, mandatory: true }},
}}
/>
</Card>
<Row gutter={10}>
<Col span={8}>
<Card title='同步转换HTML' bordered={false} style={{minHeight:200}}>
{editorState && draftToHtml(convertToRaw(editorState.getCurrentContent()))}
</Card>
</Col>
<Col span={8}>
<Card title='同步转换MarkDown' bordered={false} style={{minHeight:200}}>
{editorState && draftToMarkdown(convertToRaw(editorState.getCurrentContent()))}
</Card>
</Col>
<Col span={8}>
<Card title='同步转换JSON' bordered={false} style={{minHeight:200}}>
{JSON.stringify(contentState, null, 4)}
</Card>
</Col>
</Row>
<BackTop visibilityHeight={200} style={{right: 50}}/>
</div>
)
}
Example #5
Source File: contestEditor.js From turqV2 with GNU General Public License v3.0 | 5 votes |
_handleMarkdownChange(editorState, name) {
var raw = convertToRaw(editorState.getCurrentContent());
var markdown = draftToMarkdown(raw)
this.setState({
contest: { ...this.state.contest, [name]: markdown }
});
}
Example #6
Source File: Reviews.js From Next.js-e-commerce-online-store with MIT License | 4 votes |
export default function Reviews({ id, reviewList }) {
const [ isEditorReadOnly, setIsEditorReadOnly ] = useState(false)
const [ sameEmailError, setSameEmailError ] = useState(false)
const formik = useFormik({
initialValues: { name: '', email: '', message: '' },
onSubmit: async (values, { resetForm }) => {
setIsEditorReadOnly(true)
await fetch(`/api/postReview?productId=${id}&name=${values.name}&email=${values.email}&reviewText=${encodeURIComponent(values.message)}`)
.then(res => {
if (res.status >= 400) {
if (res.status === 400) {
console.log(res.status, res)
setSameEmailError(res.statusText)
const err = new Error(res.statustext)
setIsEditorReadOnly(false)
throw err
} else if (res.status > 400) {
setSameEmailError(false)
const err = new Error('Error')
setIsEditorReadOnly(false)
throw err
}
}
return res.json()
})
.then(data => {
resetForm()
setEditorState(EditorState.push(editorState, ContentState.createFromText('')))
setSameEmailError(false)
const publishedReview = data.data.createReview.data
reviewList.push(publishedReview)
setIsEditorReadOnly(false)
const headingElement = document.getElementById('heading')
headingElement.scrollIntoView({ behavior: 'smooth' })
})
.catch(err => console.error(err))
},
validationSchema: schema
})
const [ reviews, setReviews ] = useState(reviewList)
const value = formik.values.message
const prepareDraft = value => {
const draft = htmlToDraft(value)
const contentState = ContentState.createFromBlockArray(draft.contentBlocks)
const editorState = EditorState.createWithContent(contentState)
return editorState
}
const setFieldValue = val => formik.setFieldValue('message', val)
const [ editorState, setEditorState ] = useState(value ? prepareDraft(value) : EditorState.createEmpty())
const onEditorStateChange = editorState => {
const forFormik = draftToHtml(
convertToRaw(editorState.getCurrentContent())
)
setFieldValue(forFormik)
setEditorState(editorState)
}
return (
<ReviewsDiv>
<div className="heading" id="heading">
{
reviews.length === 0
? 'No reviews so far. Be the first!'
: 'Reviews'
}
</div>
<div className="reviews">
{
reviews
.sort((a, b) => (
// sort by date, newest first ↓
new Date(b.attributes.createdAt).getTime() - new Date(a.attributes.createdAt).getTime()
))
.map(review => (
<div className="review" key={review.id}>
<div>
Reviewed at <b>{review.attributes.createdAt.slice(0, 10)}</b> by <b>{review.attributes.name}</b>:
</div>
<div dangerouslySetInnerHTML={{__html: review.attributes.reviewText}} className="review-text"></div>
</div>
))
}
</div>
<form className="form" onSubmit={formik.handleSubmit}>
<div className="input-group">
<div className="input-group-prepend">
<span className="input-group-text" id="inputGroup-sizing-default">Name</span>
</div>
<input
type="text"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-default"
pattern="[A-Za-z ]{1,32}"
title="1 to 32 letters, no special symbols, except space"
minLength="1"
name="name"
id="name"
required
className="form-control"
value={formik.values.name}
onChange={formik.handleChange}
/>
</div>
{formik.errors.name && <h1 className="feedback-msgs">{formik.errors.name}</h1>}
<div className="input-group">
<div className="input-group-prepend">
<span className="input-group-text" id="inputGroup-sizing-default">E-mail</span>
</div>
<input
type="email"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-default"
minLength="3"
name="email"
id="email"
required
className="form-control"
value={formik.values.email}
onChange={formik.handleChange}
/>
</div>
{formik.errors.email && <h1 className="feedback-msgs">{formik.errors.email}</h1>}
<div className="editor-top-wrapper">
<Editor
editorState={editorState}
readOnly={isEditorReadOnly}
toolbarHidden={isEditorReadOnly}
toolbarClassName="toolbar"
wrapperClassName="wrapper"
editorClassName="editor"
onEditorStateChange={onEditorStateChange}
toolbar={{
options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'link', 'embedded', 'emoji', 'image', 'remove', 'history'],
colorPicker: { popupClassName: 'colorPickerPopup' },
link: { popupClassName: 'linkPopup' },
emoji: { popupClassName: 'emojiPopup' },
embedded: { popupClassName: 'embeddedPopup' },
image: { popupClassName: 'imagePopup' }
}}
/>
</div>
{formik.errors.message && <div className="feedback-msgs">{formik.errors.message}</div>}
{
sameEmailError
? <div className="feedback-msgs">{sameEmailError}</div>
: null
}
<button type="submit" className="post-button btn btn-primary" disabled={isEditorReadOnly}>
Post Review
</button>
</form>
</ReviewsDiv>
)
}
Example #7
Source File: PublicationEditor.js From paras-landing with GNU General Public License v3.0 | 4 votes |
PublicationEditor = ({ isEdit = false, pubDetail = null, draftDetail = [] }) => {
const toast = useToast()
const router = useRouter()
const { localeLn } = useIntl()
const [preventLeaving, setPreventLeaving] = useState(true)
const [showLeavingConfirmation, setShowLeavingConfirmation] = useState(false)
const [isPubDetail, setIsPubDetail] = useState(false)
usePreventRouteChangeIf(preventLeaving, (url) => {
redirectUrl = url
setShowLeavingConfirmation(true)
})
const [title, setTitle] = useState(
convertTextToEditorState(pubDetail?.title || draftDetail[0]?.title)
)
const [subTitle, setSubTitle] = useState(
pubDetail?.description || draftDetail[0]?.description || ''
)
const [thumbnail, setThumbnail] = useState(pubDetail?.thumbnail || draftDetail[0]?.thumbnail)
const [content, setContent] = useState(
generateEditorState(pubDetail?.content || draftDetail[0]?.content)
)
const [showAlertErr, setShowAlertErr] = useState(false)
const [embeddedCards, setEmbeddedCards] = useState([])
const [embeddedCollections, setEmbeddedCollections] = useState([])
const [showModal, setShowModal] = useState(null)
const [isSubmitting, setIsSubmitting] = useState(false)
const [isDraftIn, setIsDraftIn] = useState(false)
const [searchToken, setSearchToken] = useState('')
const [searchCollection, setSearchCollection] = useState('')
const [currentDraftStorage, setCurrentDraftStorage] = useState()
const currentUser = WalletHelper.currentUser
const uid = uuidv4()
useEffect(() => {
if (pubDetail !== null) setIsPubDetail(true)
}, [])
useEffect(() => {
const draftStorage = JSON.parse(localStorage.getItem('draft-publication'))
const currentUserDraft = draftStorage?.filter(
(item) => item.author_id === currentUser?.accountId
)
setCurrentDraftStorage(currentUserDraft)
}, [])
useEffect(() => {
if (isEdit) {
fetchToken()
fetchCollection()
}
}, [])
const fetchToken = async () => {
let token = []
pubDetail?.contract_token_ids?.map(async (tokenId) => {
const [contractTokenId, token_id] = tokenId.split('/')
const [contractId, tokenSeriesId] = contractTokenId.split('::')
const url = process.env.V2_API_URL
const res = await axios({
url: url + (token_id ? `/token` : `/token-series`),
method: 'GET',
params: token_id
? {
token_id: token_id,
}
: {
contract_id: contractId,
token_series_id: tokenSeriesId,
},
})
const _token = (await res.data.data.results[0]) || null
token = [...token, _token]
setEmbeddedCards(token)
})
}
const fetchCollection = async () => {
if (pubDetail?.isComic) {
let comic = []
pubDetail?.collection_ids?.map(async (comicId) => {
const url = process.env.COMIC_API_URL
const res = await axios({
url: url + `/comics`,
method: 'GET',
params: {
comic_id: comicId,
},
})
const _comic = (await res.data.data.results[0]) || null
comic = [...comic, _comic]
setEmbeddedCollections(comic)
})
} else {
let collection = []
pubDetail?.collection_ids?.map(async (collectionId) => {
const url = process.env.V2_API_URL
const res = await axios({
url: url + `/collections`,
method: 'GET',
params: {
collection_id: collectionId,
},
})
const _collection = (await res.data.data.results[0]) || null
collection = [...collection, _collection]
setEmbeddedCollections(collection)
})
}
}
const getDataFromTokenId = async () => {
const { token_id, token_series_id } = parseGetTokenIdfromUrl(searchToken)
if (token_id) {
const res = await axios.get(`${process.env.V2_API_URL}/token`, {
params: {
token_id: token_id,
contract_id: token_series_id.split('::')[0],
},
})
const token = (await res.data.data.results[0]) || null
if (token) {
setEmbeddedCards([...embeddedCards, token])
setShowModal(null)
setSearchToken('')
} else {
showToast('Please enter correct url')
}
return
}
if (token_series_id.split('::')[1]) {
const res = await axios.get(`${process.env.V2_API_URL}/token-series`, {
params: {
token_series_id: token_series_id.split('::')[1],
contract_id: token_series_id.split('::')[0],
},
})
const token = (await res.data.data.results[0]) || null
if (token) {
setEmbeddedCards([...embeddedCards, token])
setShowModal(null)
setSearchToken('')
} else {
showToast('Please enter correct url')
}
return
}
showToast('Please enter correct url')
}
const getDataFromCollectionId = async () => {
const { collection_id } = parseGetCollectionIdfromUrl(searchCollection)
if (embeddedCollections.some((col) => col.collection_id === collection_id)) {
showToast('You have added this collection')
return
}
const res = await axios.get(`${process.env.V2_API_URL}/collections`, {
params: {
collection_id: collection_id,
},
})
const collection = (await res.data.data.results[0]) || null
if (collection) {
setEmbeddedCollections([...embeddedCollections, collection])
setShowModal(null)
setSearchCollection('')
} else {
showToast('Please enter correct url')
}
return
}
const getTokenIds = () => {
return embeddedCards.map((token) => {
let tokenId = `${token.contract_id}::${token.token_series_id}`
if (token.token_id) {
tokenId += `/${token.token_id}`
}
return tokenId
})
}
const getCollectionIds = () => {
return embeddedCollections.map((coll) => coll.collection_id)
}
const showToast = (msg, type = 'error') => {
toast.show({
text: <div className="font-semibold text-center text-sm">{msg}</div>,
type: type,
duration: 1500,
})
}
const showCardModal = () => {
embeddedCards.length === 6 ? showToast('Maximum 6 cards') : setShowModal('card')
}
const showCollectionModal = () => {
embeddedCollections.length === 6
? showToast('Maximum 6 collection')
: setShowModal('collection')
}
const postPublication = async () => {
if (!thumbnail || !subTitle) {
let error = []
if (!thumbnail) error.push('Thumbnail')
if (!subTitle) error.push('Description')
toast.show({
text: (
<div className="font-semibold text-center text-sm">{error.join(' and ')} is required</div>
),
type: 'error',
duration: null,
})
return
}
setIsSubmitting(true)
setPreventLeaving(false)
const entityMap = await uploadImage()
const _thumbnail = await uploadThumbnail()
const data = {
title: title.getCurrentContent().getPlainText(),
thumbnail: _thumbnail,
description: subTitle,
content: {
blocks: convertToRaw(content.getCurrentContent()).blocks,
entityMap: entityMap,
},
contract_token_ids: getTokenIds(),
collection_ids: getCollectionIds(),
}
try {
const url = `${process.env.V2_API_URL}/publications`
const res = await axios(
!isPubDetail && draftDetail.length > 0
? {
url: url,
method: 'post',
data: data,
headers: {
authorization: await WalletHelper.authToken(),
},
}
: {
url: isEdit ? url + `/${pubDetail._id}` : url,
method: isEdit ? 'put' : 'post',
data: data,
headers: {
authorization: await WalletHelper.authToken(),
},
}
)
if (!isPubDetail && draftDetail.length > 0) deleteDraft(draftDetail[0]._id)
const pub = res.data.data
const routerUrl = `/publication/${pub.slug}-${pub._id}`
setTimeout(() => {
router.push(routerUrl)
}, 1000)
} catch (err) {
sentryCaptureException(err)
const msg = err.response?.data?.message || `Something went wrong, try again later`
showToast(msg)
setIsSubmitting(false)
setPreventLeaving(true)
}
}
const saveDraft = async () => {
let checkTotalDraft = false
if (!window.location.href.includes('edit')) checkTotalDraft = currentDraftStorage?.length >= 10
if (checkTotalDraft) {
toast.show({
text: (
<div className="font-semibold text-center text-sm">
{' '}
{checkTotalDraft && 'The maximum number of drafts is 10 drafts'}
</div>
),
type: 'error',
duration: null,
})
return
}
setIsDraftIn(true)
setPreventLeaving(false)
const entityMap = await uploadImage()
const _thumbnail = await uploadThumbnail()
const data = {
_id: uid,
author_id: currentUser.accountId,
title: title.getCurrentContent().getPlainText(),
draft: true,
thumbnail: _thumbnail,
description: subTitle,
content: {
blocks: convertToRaw(content.getCurrentContent()).blocks,
entityMap: entityMap,
},
contract_token_ids: getTokenIds(),
}
let draftStorage = JSON.parse(localStorage.getItem('draft-publication')) || []
const draftCurrentEdit = JSON.parse(localStorage.getItem('edit-draft'))
let checkDraft = []
if (draftCurrentEdit !== null) {
checkDraft = draftStorage.find((item) => item._id === draftCurrentEdit[0]._id)
}
if (checkDraft && window.location.href.includes('edit')) {
checkDraft.title = data.title
checkDraft.thumbnail = data.thumbnail
checkDraft.description = data.subTitle
checkDraft.content = data.content
checkDraft.contract_token_ids = data.contract_token_ids
draftStorage.push(checkDraft)
draftStorage.pop()
localStorage.setItem('draft-publication', JSON.stringify(draftStorage))
} else {
draftStorage.push(data)
localStorage.setItem('draft-publication', JSON.stringify(draftStorage))
}
const routerUrl = `/${currentUser.accountId}/publication`
router.push(routerUrl)
}
const deleteDraft = (_id) => {
const dataDraftPublication = JSON.parse(localStorage.getItem('draft-publication'))
const deleteItem = dataDraftPublication.filter((item) => item._id !== _id)
localStorage.setItem('draft-publication', JSON.stringify(deleteItem))
if (dataDraftPublication.length === 1) localStorage.removeItem('draft-publication')
}
const uploadImage = async () => {
let { entityMap } = convertToRaw(content.getCurrentContent())
const formData = new FormData()
for (let key in entityMap) {
if (entityMap[key].type === 'IMAGE' && !entityMap[key].data.src?.includes('ipfs://')) {
const file = dataURLtoFile(entityMap[key].data.src, key)
formData.append('files', file, key)
}
}
const resp = await axios.post(`${process.env.V2_API_URL}/uploads`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
authorization: await WalletHelper.authToken(),
},
})
let idx = 0
for (let key in entityMap) {
if (entityMap[key].type === 'IMAGE' && !entityMap[key].data.src?.includes('ipfs://')) {
entityMap[key].data.src = resp.data.data[idx]
idx++
}
}
return entityMap
}
const uploadThumbnail = async () => {
if (thumbnail !== undefined) {
// eslint-disable-next-line no-unused-vars
const [protocol, path] = thumbnail.split('://')
if (protocol === 'ipfs') {
return thumbnail
}
const formData = new FormData()
formData.append('files', dataURLtoFile(thumbnail), 'thumbnail')
const resp = await axios.post(`${process.env.V2_API_URL}/uploads`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
authorization: await WalletHelper.authToken(),
},
})
return resp.data.data[0]
}
}
const updateThumbnail = async (e) => {
if (e.target.files[0]) {
if (e.target.files[0].size > 3 * 1024 * 1024) {
toast.show({
text: (
<div className="font-semibold text-center text-sm">{localeLn('MaximumSize3MB')}</div>
),
type: 'error',
duration: null,
})
return
}
const compressedImg =
e.target.files[0].type === 'image/gif'
? e.target.files[0]
: await compressImg(e.target.files[0])
setThumbnail(await readFileAsUrl(compressedImg))
}
}
const onPressContinue = () => {
const { entityMap } = convertToRaw(content.getCurrentContent())
if (!thumbnail) {
for (let key in entityMap) {
if (entityMap[key].type === 'IMAGE') {
setThumbnail(entityMap[key].data.src || thumbnail)
break
}
}
}
setShowModal('final')
}
return (
<div className="py-16 min-h-screen">
{showModal === 'card' && (
<Modal close={() => setShowModal(null)} closeOnBgClick={true} closeOnEscape={true}>
<div className="w-full max-w-md p-4 m-auto bg-dark-primary-2 rounded-md overflow-hidden">
<div className="m-auto">
<label className="mb-4 block text-white text-2xl font-bold">
{localeLn('AddCardToPublication')}
</label>
<input
type="text"
name="Token"
onChange={(e) => setSearchToken(e.target.value)}
value={searchToken}
className={`resize-none h-auto focus:border-gray-100 mb-4`}
placeholder="Url of the Token"
/>
<p className="text-gray-300 text-sm italic">Please input the link of your token</p>
<p className="text-gray-300 text-sm italic">https://paras.id/token/x.paras.near::1</p>
<button
className="font-semibold mt-4 py-3 w-full rounded-md bg-primary text-white"
disabled={!searchToken}
onClick={getDataFromTokenId}
>
{localeLn('AddCard')}
</button>
</div>
</div>
</Modal>
)}
{showModal === 'collection' && (
<Modal
close={() => {
setShowModal(null)
}}
closeOnBgClick={true}
closeOnEscape={true}
>
<div className="w-full max-w-md p-4 m-auto bg-dark-primary-2 rounded-md overflow-hidden">
<div className="m-auto">
<label className="mb-4 block text-white text-2xl font-bold">
{localeLn('AddCollectionToPublication')}
</label>
<input
type="text"
name="video"
onChange={(e) => setSearchCollection(e.target.value)}
value={searchCollection}
className={`resize-none h-auto focus:border-gray-100 mb-4 text-black`}
placeholder="Url of the Collection"
/>
<p className="text-gray-300 text-sm italic">
Please input the link of your collection
</p>
<p className="text-gray-300 text-sm italic">https://paras.id/collection/paradigm</p>
<button
className="font-semibold mt-4 py-3 w-full rounded-md bg-primary text-white"
disabled={!searchCollection}
onClick={getDataFromCollectionId}
>
{localeLn('AddCollection')}
</button>
</div>
</div>
</Modal>
)}
{showModal === 'final' && (
<Modal close={() => setShowModal(null)} closeOnBgClick={false} closeOnEscape={false}>
<div className="w-full max-h-screen max-w-3xl p-4 m-auto bg-dark-primary-2 rounded-md overflow-hidden overflow-y-auto">
<div className="flex justify-between">
<h1 className="mb-4 block text-white text-2xl font-bold">
{isEdit ? 'Edit Publication' : 'Preview Publication'}
</h1>
<div onClick={() => setShowModal(null)}>
<IconX size={24} className="cursor-pointer" />
</div>
</div>
<div className="flex flex-col md:flex-row -mx-2">
<div className="w-full md:w-1/2 px-2">
<h1 className="mb-2 block text-white text-md font-medium">
{localeLn('Thumbnail')}
</h1>
<div className="bg-white h-64 mb-4 overflow-hidden relative rounded-md">
<div className="absolute inset-0 flex items-center justify-center">
<div className="bg-opacity-75 bg-black p-2 rounded-md">
<div className="flex items-center">
<svg
className="m-auto"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M4 2H20C21.1046 2 22 2.89543 22 4V20C22 21.1046 21.1046 22 20 22H4C2.89543 22 2 21.1046 2 20V4C2 2.89543 2.89543 2 4 2ZM4 4V15.5858L8 11.5858L11.5 15.0858L18 8.58579L20 10.5858V4H4ZM4 20V18.4142L8 14.4142L13.5858 20H4ZM20 20H16.4142L12.9142 16.5L18 11.4142L20 13.4142V20ZM14 8C14 6.34315 12.6569 5 11 5C9.34315 5 8 6.34315 8 8C8 9.65685 9.34315 11 11 11C12.6569 11 14 9.65685 14 8ZM10 8C10 7.44772 10.4477 7 11 7C11.5523 7 12 7.44772 12 8C12 8.55228 11.5523 9 11 9C10.4477 9 10 8.55228 10 8Z"
fill="rgba(255,255,255,1)"
/>
</svg>
<p className="text-white font-semibold ml-2 text-sm">
{localeLn('UpdateThumbnail3MB')}
</p>
</div>
</div>
</div>
<input
className="cursor-pointer w-full opacity-0 absolute inset-0"
type="file"
accept="image/*"
onChange={updateThumbnail}
/>
{thumbnail && (
<img
className="w-full h-full object-cover m-auto"
src={parseImgUrl(thumbnail, null, {
width: `600`,
})}
/>
)}
</div>
</div>
<div className="w-full md:w-1/2 px-2">
<h1 className="mb-2 block text-white text-md font-medium">{localeLn('Title')}</h1>
<input
type="text"
name="Title"
disabled={true}
value={title.getCurrentContent().getPlainText()}
className={`resize-none h-auto focus:border-gray-100`}
placeholder="Preview Title"
/>
<h1 className="mt-3 mb-2 block text-white text-md font-medium">
{localeLn('Description')}
</h1>
<textarea
type="text"
name="SubTitle"
onChange={(e) => setSubTitle(e.target.value)}
value={subTitle}
className={`resize-none focus:border-gray-100 h-24`}
placeholder="Preview Description"
/>
<div className="flex gap-4">
<button
className="font-semibold mt-3 py-3 w-40 rounded-md bg-primary text-white"
disabled={isSubmitting}
onClick={postPublication}
>
{isSubmitting ? 'Publishing...' : 'Publish'}
</button>
{!isPubDetail && (
<button
className="font-semibold mt-3 py-3 w-40 rounded-md border-2 border-white text-white"
disabled={isDraftIn}
onClick={saveDraft}
>
{isDraftIn ? 'Draft in...' : 'Draft'}
</button>
)}
</div>
</div>
</div>
</div>
</Modal>
)}
{showLeavingConfirmation && (
<Modal close={() => setShowLeavingConfirmation(false)} closeOnBgClick closeOnEscape>
<div className="w-full max-w-xs p-4 m-auto bg-gray-100 rounded-md overflow-y-auto max-h-screen">
<div className="w-full">{localeLn('SureToLeavepage')}</div>
<div className="flex space-x-4">
<button
className="w-full outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-primary text-gray-100"
onClick={() => {
setPreventLeaving(false)
setTimeout(() => {
setShowLeavingConfirmation(false)
router.push(redirectUrl)
}, 100)
}}
>
OK
</button>
<button
className="w-full outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-white text-primary"
onClick={() => setShowLeavingConfirmation(false)}
>
{localeLn('Cancel')}
</button>
</div>
</div>
</Modal>
)}
{showAlertErr && (
<Modal close={() => setShowAlertErr(false)}>
<div className="w-full max-w-xs p-4 m-auto bg-gray-100 rounded-md overflow-y-auto max-h-screen">
<div className="w-full">{showAlertErr}</div>
<button
className="w-full outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-primary text-gray-100"
onClick={() => setShowAlertErr(false)}
>
{localeLn('OK')}
</button>
</div>
</Modal>
)}
<div className="mx-auto max-w-3xl px-4">
<TextEditor
content={content}
setContent={setContent}
title={title}
setTitle={setTitle}
onPressAddCard={getDataFromTokenId}
showCardModal={showCardModal}
showCollectionModal={showCollectionModal}
/>
</div>
{embeddedCollections.length !== 0 && (
<div className="max-w-4xl mx-auto px-4 pt-16">
<div className="rounded-md p-4 md:p-8">
<h4 className="text-white font-semibold text-3xl mb-4 text-center">
{pubDetail?.isComic ? 'Comics' : localeLn('Collections')}
</h4>
<div
className={`md:flex md:flex-wrap ${
embeddedCollections.length <= 3 && 'justify-center'
}`}
>
{embeddedCollections.map((coll, key) => (
<div key={key} className="w-full md:w-1/2 lg:w-1/3 flex-shrink-0 p-4">
<CollectionPublication
localCollection={coll}
onDelete={() => {
const temp = embeddedCollections.filter(
(x) => x.collection_id != coll.collection_id
)
setEmbeddedCollections(temp)
}}
pubDetail={pubDetail}
/>
</div>
))}
</div>
</div>
</div>
)}
{embeddedCards.length !== 0 && (
<div className="max-w-4xl mx-auto px-4 pt-16">
<div className=" border-2 border-dashed border-gray-800 rounded-md p-4 md:p-8">
<h4 className="text-white font-semibold text-3xl mb-4 text-center">
{localeLn('CardCollectibles')}
</h4>
<div
className={`md:flex md:flex-wrap ${embeddedCards.length <= 3 && 'justify-center'}`}
>
{embeddedCards.map((card) => (
<div key={card._id} className="w-full md:w-1/2 lg:w-1/3 flex-shrink-0 p-8">
<CardPublication
localToken={card}
deleteCard={() => {
const temp = embeddedCards.filter(
(x) => x.token_series_id != card.token_series_id
)
setEmbeddedCards(temp)
}}
/>
</div>
))}
</div>
</div>
</div>
)}
<div className="flex items-center max-w-3xl mx-auto px-4 pt-8">
<button
className="font-semibold py-3 w-32 rounded-md bg-primary text-white"
onClick={onPressContinue}
disabled={title === '' || !content.getCurrentContent().hasText()}
>
{localeLn('Continue')}
</button>
<DraftPublication onCreatePublication />
</div>
</div>
)
}
Example #8
Source File: convertToHTML.js From the-eye-knows-the-garbage with MIT License | 4 votes |
convertToHTML = function convertToHTML(_ref) {
var _ref$styleToHTML = _ref.styleToHTML,
styleToHTML = _ref$styleToHTML === void 0 ? {} : _ref$styleToHTML,
_ref$blockToHTML = _ref.blockToHTML,
blockToHTML = _ref$blockToHTML === void 0 ? {} : _ref$blockToHTML,
_ref$entityToHTML = _ref.entityToHTML,
entityToHTML = _ref$entityToHTML === void 0 ? defaultEntityToHTML : _ref$entityToHTML;
return function (contentState) {
invariant(contentState !== null && contentState !== undefined, 'Expected contentState to be non-null');
var getBlockHTML;
if (blockToHTML.__isMiddleware === true) {
getBlockHTML = blockToHTML(blockTypeObjectFunction(defaultBlockHTML));
} else {
getBlockHTML = accumulateFunction(blockTypeObjectFunction(blockToHTML), blockTypeObjectFunction(defaultBlockHTML));
}
var rawState = convertToRaw(contentState);
var listStack = [];
var result = rawState.blocks.map(function (block) {
var type = block.type,
depth = block.depth;
var closeNestTags = '';
var openNestTags = '';
var blockHTMLResult = getBlockHTML(block);
if (!blockHTMLResult) {
throw new Error("convertToHTML: missing HTML definition for block with type ".concat(block.type));
}
if (!blockHTMLResult.nest) {
// this block can't be nested, so reset all nesting if necessary
closeNestTags = listStack.reduceRight(function (string, nestedBlock) {
return string + getNestedBlockTags(getBlockHTML(nestedBlock), depth).nestEnd;
}, '');
listStack = [];
} else {
while (depth + 1 !== listStack.length || type !== listStack[depth].type) {
if (depth + 1 === listStack.length) {
// depth is right but doesn't match type
var blockToClose = listStack[depth];
closeNestTags += getNestedBlockTags(getBlockHTML(blockToClose), depth).nestEnd;
openNestTags += getNestedBlockTags(getBlockHTML(block), depth).nestStart;
listStack[depth] = block;
} else if (depth + 1 < listStack.length) {
var _blockToClose = listStack[listStack.length - 1];
closeNestTags += getNestedBlockTags(getBlockHTML(_blockToClose), depth).nestEnd;
listStack = listStack.slice(0, -1);
} else {
openNestTags += getNestedBlockTags(getBlockHTML(block), depth).nestStart;
listStack.push(block);
}
}
}
var innerHTML = blockInlineStyles(blockEntities(encodeBlock(block), rawState.entityMap, entityToHTML), styleToHTML);
var blockHTML = getBlockTags(getBlockHTML(block));
var html;
if (typeof blockHTML === 'string') {
html = blockHTML;
} else {
html = blockHTML.start + innerHTML + blockHTML.end;
}
if (innerHTML.length === 0 && Object.prototype.hasOwnProperty.call(blockHTML, 'empty')) {
if (React.isValidElement(blockHTML.empty)) {
html = ReactDOMServer.renderToStaticMarkup(blockHTML.empty);
} else {
html = blockHTML.empty;
}
}
return closeNestTags + openNestTags + html;
}).join('');
result = listStack.reduce(function (res, nestBlock) {
return res + getNestedBlockTags(getBlockHTML(nestBlock), nestBlock.depth).nestEnd;
}, result);
return result;
};
}
Example #9
Source File: AddEditActivity.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
AddEditActivity = props => {
let history = useHistory();
const dateFrom = "dateFrom";
const dateTo = "dateTo";
const [editorState, setEditorState] = useState(EditorState.createEmpty());
const [backDrop, setBackDrop] = useState(false);
const [formState, setFormState] = useState({
isValid: false,
values: {
dateFrom: moment(),
dateTo: moment()
},
touched: {},
errors: {},
isSuccess: false,
showPassword: false,
editActivity: props.location.editActivity
? props.location.editActivity
: false,
dataForEdit: props.location.dataForEdit
? props.location.dataForEdit
: false,
counter: 0,
testCounter: 0,
stream: [],
files: null,
descriptionError: false,
discriptionMinLengthError: false,
previewFile: {},
showPreview: false,
showEditPreview: props.location.editActivity
? props.location.dataForEdit.upload_logo
? true
: false
: false,
showNoImage: props.location.editActivity
? false
: props.location.editActivity
});
if (formState.dataForEdit && !formState.counter) {
if (props.location["dataForEdit"]) {
if (props.location["dataForEdit"]["title"]) {
formState.values["activityname"] =
props.location["dataForEdit"]["title"];
}
if (props.location["dataForEdit"]["activitytype"]) {
formState.values["activitytype"] =
props.location["dataForEdit"]["activitytype"]["id"];
}
if (
props.location["dataForEdit"]["academic_year"] &&
props.location["dataForEdit"]["academic_year"]["id"]
) {
formState.values["academicyear"] =
props.location["dataForEdit"]["academic_year"]["id"];
}
if (props.location["dataForEdit"]["streams"]) {
formState.values["stream"] = props.location["dataForEdit"]["streams"];
}
if (props.location["dataForEdit"]["address"]) {
formState.values["address"] = props.location["dataForEdit"]["address"];
}
if (props.location["dataForEdit"]["education_year"]) {
formState.values["educationyear"] =
props.location["dataForEdit"]["education_year"];
}
if (props.location["dataForEdit"]["activity_status"]) {
formState.values["activitystatus"] =
props.location["dataForEdit"]["activity_status"];
}
if (
props.location["dataForEdit"]["question_set"] &&
props.location["dataForEdit"]["question_set"]
) {
formState.values["questionSet"] =
props.location["dataForEdit"]["question_set"]["id"];
}
if (props.location["dataForEdit"]["description"]) {
// formState.values["description"] = props["dataForEdit"]["description"];
const blocksFromHtml = htmlToDraft(
props.location["dataForEdit"]["description"]
);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(
contentBlocks,
entityMap
);
const editorState = EditorState.createWithContent(contentState);
setEditorState(editorState);
}
if (props.location["dataForEdit"]["trainer_name"]) {
formState.values["trainer"] =
props.location["dataForEdit"]["trainer_name"];
}
if (
props.location["dataForEdit"]["contact"] &&
props.location["dataForEdit"]["contact"]["id"]
) {
formState.values["college"] =
props.location["dataForEdit"]["contact"]["id"];
}
if (props.location["dataForEdit"]["start_date_time"]) {
formState.values[dateFrom] = moment(
props.location["dataForEdit"]["start_date_time"]
);
}
if (props.location["dataForEdit"]["end_date_time"]) {
formState.values[dateTo] = moment(
props.location["dataForEdit"]["end_date_time"]
);
}
if (
props.location["dataForEdit"]["upload_logo"] &&
props.location["dataForEdit"]["upload_logo"]["id"]
) {
formState.files = props.location["dataForEdit"]["upload_logo"];
// formState.values["files"] =
// props.location["dataForEdit"]["upload_logo"]["name"];
}
}
formState.counter += 1;
}
if (props.location.state && !formState.counter) {
if (props.location.state.contactNumber && props.location.state.otp) {
formState.values["contact"] = props.location.state.contactNumber;
formState.values["otp"] = props.location.state.otp;
}
formState.counter += 1;
}
// const [selectedDateFrom, setSelectedDateFrom] = React.useState(new Date());
// const [selectedDateTo, setSelectedDateTo] = React.useState(new Date());
const { setLoaderStatus } = useContext(LoaderContext);
const educationyearlist = [
{ name: "First", id: "First" },
{ name: "Second", id: "Second" },
{ name: "Third", id: "Third" }
];
const activityNameList = [
{ name: "Soft Skills 1", id: "Soft Skills 1" },
{ name: "Soft Skills 2", id: "Soft Skills 2" },
{ name: "Career Awareness 1", id: "Career Awareness 1" },
{ name: "Career Awareness 2", id: "Career Awareness 2" },
{ name: "Job Preparation 1", id: "Job Preparation 1" },
{ name: "Job Preparation 2", id: "Job Preparation 2" },
{ name: "Job Preparation 3", id: "Job Preparation 3" },
{ name: "Industrial Visit", id: "Industrial Visit" },
{ name: "Industry Talk", id: "Industry Talk" }
];
const activityStatus = [
{ name: "Scheduled", id: "scheduled" },
{ name: "Completed", id: "completed" },
{ name: "Cancelled", id: "cancelled" }
];
const [stream, setStream] = useState([]);
const [isFailed, setIsFailed] = useState(false);
const classes = useStyles();
const [collegelist, setcollegelist] = useState(
props.collegeListForTest ? props.collegeListForTest : []
);
const [streamlist, setstreamlist] = useState(
props.streamListForTest ? props.streamListForTest : []
);
const [collegeStreamList, setCollegeStreamList] = useState(
props.collegeStreamListForTest ? props.collegeStreamListForTest : []
);
const [activityType, setActivityType] = useState(
props.activityTypeListForTest ? props.activityTypeListForTest : []
);
const [questionSetData, setQuestionSetData] = useState(
props.questionSetListForTest ? props.questionSetListForTest : []
);
if (
!formState.dataForEdit &&
props.isDataForTesting &&
!formState.testCounter
) {
const html = "<p>Test Data</p>";
const contentBlock = htmlToDraft(html);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(
contentBlock.contentBlocks
);
const editorState = EditorState.createWithContent(contentState);
setEditorState(editorState);
formState.testCounter += 1;
}
}
useEffect(() => {
serviceProvider
.serviceProviderForGetRequest(QUESTION_SET)
.then(res => {
setQuestionSetData(res.data);
})
.catch(error => {});
getColleges();
getStreams();
getActivityTypes();
}, []);
const getActivityTypes = async () => {
const activityTypeUrl =
strapiApiConstants.STRAPI_DB_URL +
strapiApiConstants.STRAPI_ACTIVITY_TYPE;
await serviceProvider
.serviceProviderForGetRequest(activityTypeUrl)
.then(res => {
setActivityType(res.data);
})
.catch(error => {});
};
const getStreams = () => {
axios
.get(strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_STREAMS)
.then(res => {
const list = res.data.map(({ id, name }) => ({
id,
name
}));
setstreamlist(list);
if (formState.dataForEdit) {
const streamIds = props.location["dataForEdit"]["streams"].map(
stream => stream.id
);
const selectedStream = list.filter(stream => {
if (includes(streamIds, stream.id)) {
return stream;
}
});
setStream(selectedStream);
}
});
};
useEffect(() => {
setLoaderStatus(true);
if (
formState.values.hasOwnProperty("college") &&
formState.values["college"] &&
collegelist.length > 0
) {
const college = collegelist.find(
college => college.contact.id == formState.values["college"]
);
const collegeStreamIds = college.stream_strength.map(s => s.stream.id);
const list = streamlist.filter(stream => {
if (includes(collegeStreamIds, stream.id)) {
return stream;
}
});
setCollegeStreamList(list);
}
setLoaderStatus(false);
}, [formState.values["college"], collegelist, streamlist]);
const handleSubmit = event => {
event.preventDefault();
setBackDrop(true);
let isValid = false;
let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
formState.values,
ActivityFormSchema
);
if (checkAllFieldsValid) {
/** Evaluated only if all keys are valid inside formstate */
formState.errors = formUtilities.setErrors(
formState.values,
ActivityFormSchema,
true,
dateFrom,
dateTo
);
if (formUtilities.checkEmpty(formState.errors)) {
isValid = true;
}
} else {
/** This is used to find out which all required fields are not filled */
formState.values = formUtilities.getListOfKeysNotPresent(
formState.values,
ActivityFormSchema
);
formState.errors = formUtilities.setErrors(
formState.values,
ActivityFormSchema,
true,
dateFrom,
dateTo
);
}
formState.descriptionError = false;
if (
convertToRaw(editorState.getCurrentContent()).blocks &&
convertToRaw(editorState.getCurrentContent()).blocks.length
) {
let arrayToCheckIn = convertToRaw(editorState.getCurrentContent()).blocks;
let validationCounter = 0;
let validationMinCounter = 0;
for (let i in arrayToCheckIn) {
if (
arrayToCheckIn[i]["text"] &&
arrayToCheckIn[i]["text"].trim().length !== 0
) {
validationCounter += 1;
break;
}
}
if (validationCounter === 0) {
formState.descriptionError = true;
}
for (let i in arrayToCheckIn) {
if (
arrayToCheckIn[i]["text"] &&
arrayToCheckIn[i]["text"].trim().length > 320
) {
validationMinCounter += 1;
break;
}
}
if (validationMinCounter !== 0) {
formState.discriptionMinLengthError = true;
}
}
if (
isValid &&
!formState.descriptionError &&
!formState.discriptionMinLengthError
) {
/** CALL POST FUNCTION */
postActivityData();
/** Call axios from here */
setFormState(formState => ({
...formState,
isValid: true
}));
} else {
setBackDrop(false);
setFormState(formState => ({
...formState,
isValid: false
}));
}
};
const postActivityData = () => {
let postData;
if (formState.editActivity) {
postData = databaseUtilities.editActivity(
formState.showPreview,
formState.values["activityname"],
formState.values["activitytype"],
formState.values["college"],
formState.values[dateFrom],
formState.values[dateTo],
formState.values["educationyear"],
formState.values["address"],
draftToHtml(convertToRaw(editorState.getCurrentContent())),
formState.values["trainer"],
stream.map(stream => stream.id),
formState["dataForEdit"]["id"],
formState.files,
formState.values["questionSet"],
formState.values["activitystatus"]
);
serviceProvider
.serviceProviderForPutRequest(
strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_ACTIVITY,
formState.dataForEdit.id,
postData
)
.then(response => {
setFormState({ ...formState, isSuccess: true });
history.push({
pathname: routeConstants.MANAGE_ACTIVITY,
isDataEdited: true,
editedData: response.data,
fromEditActivity: true
});
setBackDrop(false);
})
.catch(err => {
setIsFailed(true);
setBackDrop(false);
});
} else {
postData = databaseUtilities.addActivity(
formState.values["activityname"],
formState.values["activitytype"],
formState.values["college"],
formState.values[dateFrom],
formState.values[dateTo],
formState.values["educationyear"],
formState.values["address"],
draftToHtml(convertToRaw(editorState.getCurrentContent())),
formState.values["trainer"],
stream.map(stream => stream.id),
formState.files,
formState.values["questionSet"]
);
serviceProvider
.serviceProviderForPostRequest(
strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_ACTIVITY,
postData
)
.then(({ data }) => {
history.push({
pathname: routeConstants.MANAGE_ACTIVITY,
isDataAdded: true,
addedData: data,
fromAddActivity: true
});
setBackDrop(false);
})
.catch(err => {
setIsFailed(true);
setBackDrop(false);
});
}
};
const getColleges = async () => {
await serviceProvider
.serviceProviderForGetRequest(
strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_COLLEGES,
{ pageSize: -1 }
)
.then(res => {
setcollegelist(
res.data.result.map(({ id, name, contact, stream_strength }) => ({
id,
name,
contact,
stream_strength
}))
);
});
};
const handleChangefile = e => {
e.persist();
setFormState(formState => ({
...formState,
values: {
...formState.values,
[e.target.name]: e.target.files[0].name
},
touched: {
...formState.touched,
[e.target.name]: true
},
files: e.target.files[0],
previewFile: URL.createObjectURL(e.target.files[0]),
showPreview: true,
showEditPreview: false,
showNoImage: false
}));
if (formState.errors.hasOwnProperty(e.target.name)) {
delete formState.errors[e.target.name];
}
};
const handleChange = e => {
/** TO SET VALUES IN FORMSTATE */
e.persist();
setFormState(formState => ({
...formState,
values: {
...formState.values,
[e.target.name]:
e.target.type === "checkbox" ? e.target.checked : e.target.value
},
touched: {
...formState.touched,
[e.target.name]: true
}
}));
if (formState.errors.hasOwnProperty(e.target.name)) {
delete formState.errors[e.target.name];
}
};
const handleChangeAutoComplete = (eventName, event, value) => {
/**TO SET VALUES OF AUTOCOMPLETE */
if (value !== null) {
if (eventName === "college") {
setFormState(formState => ({
...formState,
values: {
...formState.values,
[eventName]: value.contact.id
},
touched: {
...formState.touched,
[eventName]: true
}
}));
} else {
setFormState(formState => ({
...formState,
values: {
...formState.values,
[eventName]: value.id
},
touched: {
...formState.touched,
[eventName]: true
}
}));
}
if (formState.errors.hasOwnProperty(eventName)) {
delete formState.errors[eventName];
}
} else {
if (eventName === "college") {
delete formState.values["stream"];
formState.stream = [];
setCollegeStreamList([]);
setStream([]);
}
delete formState.values[eventName];
}
};
const handleStreamChange = (eventName, event, value) => {
/**TO SET VALUES OF AUTOCOMPLETE */
if (value !== null) {
setFormState(formState => ({
...formState,
values: {
...formState.values,
[eventName]: value
},
touched: {
...formState.touched,
[eventName]: true
}
}));
if (formState.errors.hasOwnProperty(eventName)) {
delete formState.errors[eventName];
}
setStream(value);
}
};
const handleDateChange = (dateObject, event) => {
if (formState.errors.hasOwnProperty(dateObject)) {
delete formState.errors[dateObject];
}
setFormState(formState => ({
...formState,
values: {
...formState.values,
[dateObject]: event
},
touched: {
...formState.touched,
[dateObject]: true
},
isStateClearFilter: false
}));
};
const hasError = field => (formState.errors[field] ? true : false);
return (
<Grid>
<Grid item xs={12} className={classes.title}>
<Typography variant="h4" gutterBottom>
{formState.editActivity
? genericConstants.EDIT_ACTIVITY_TEXT
: genericConstants.ADD_ACTIVITY_TEXT}
</Typography>
{isFailed && formState.editActivity ? (
<Collapse in={isFailed}>
<Alert
severity="error"
action={
<IconButton
aria-label="close"
color="inherit"
size="small"
onClick={() => {
setIsFailed(false);
}}
>
<CloseIcon fontSize="inherit" />
</IconButton>
}
>
{genericConstants.ALERT_ERROR_DATA_EDITED_MESSAGE}
</Alert>
</Collapse>
) : null}
{isFailed && !formState.editActivity ? (
<Collapse in={isFailed}>
<Alert
severity="error"
action={
<IconButton
aria-label="close"
color="inherit"
size="small"
onClick={() => {
setIsFailed(false);
}}
>
<CloseIcon fontSize="inherit" />
</IconButton>
}
>
{genericConstants.ALERT_ERROR_DATA_ADDED_MESSAGE}
</Alert>
</Collapse>
) : null}
</Grid>
<Grid spacing={3}>
<Card>
<form autoComplete="off" noValidate>
<CardContent>
<Grid item xs={12} md={6} xl={3}>
<Grid container className={classes.formgridInputFile}>
<Grid item md={10} xs={12}>
<div className={classes.imageDiv}>
{formState.showPreview ? (
<Img
alt="abc"
loader={<Spinner />}
className={classes.UploadImage}
src={formState.previewFile}
/>
) : null}
{!formState.showPreview && !formState.showEditPreview ? (
<div className={classes.DefaultNoImage}></div>
) : null}
{/* {formState.showEditPreview&&formState.dataForEdit.upload_logo===null? <div class={classes.DefaultNoImage}></div>:null} */}
{formState.showEditPreview &&
formState.dataForEdit["upload_logo"] !== null &&
formState.dataForEdit["upload_logo"] !== undefined &&
formState.dataForEdit["upload_logo"] !== {} ? (
<Img
src={
strapiApiConstants.STRAPI_DB_URL_WITHOUT_HASH +
formState.dataForEdit["upload_logo"]["url"]
}
loader={<Spinner />}
className={classes.UploadImage}
/>
) : null}
{formState.showNoImage ? (
<Img
src="/images/noImage.png"
loader={<Spinner />}
className={classes.UploadImage}
/>
) : null}
</div>
</Grid>
</Grid>
<Grid container className={classes.MarginBottom}>
<Grid item md={10} xs={12}>
<TextField
fullWidth
id="files"
margin="normal"
name="files"
placeholder="Upload Logo"
onChange={handleChangefile}
required
type="file"
inputProps={{ accept: "image/*" }}
//value={formState.values["files"] || ""}
error={hasError("files")}
helperText={
hasError("files")
? formState.errors["files"].map(error => {
return error + " ";
})
: null
}
variant="outlined"
className={classes.inputFile}
/>
<label htmlFor={get(ActivityFormSchema["files"], "id")}>
<Button
variant="contained"
color="primary"
component="span"
fullWidth
className={classes.InputFileButton}
startIcon={<AddOutlinedIcon />}
>
ADD NEW FILE
</Button>
</label>
</Grid>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={3} className={classes.formgrid}>
<Grid item md={12} xs={12}>
<Autocomplete
id="activitytype"
className={classes.root}
options={activityType}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete("activitytype", event, value);
}}
value={
activityType[
activityType.findIndex(function (item, i) {
return item.id === formState.values.activitytype;
})
] || null
}
renderInput={params => (
<TextField
{...params}
error={hasError("activitytype")}
label="Activity Type"
variant="outlined"
name="tester"
helperText={
hasError("activitytype")
? formState.errors["activitytype"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.formgrid}>
<Grid item md={12} xs={12}>
<Autocomplete
id="activityname"
className={classes.root}
options={activityNameList}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete("activityname", event, value);
}}
value={
activityNameList[
activityNameList.findIndex(function (item, i) {
return item.id === formState.values["activityname"];
})
] || null
}
renderInput={params => (
<TextField
{...params}
error={hasError("activityname")}
label="Activity Name"
variant="outlined"
required
name="activityname"
helperText={
hasError("activityname")
? formState.errors["activityname"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12} className={"descriptionBox"}>
<Grid
className={
formState.descriptionError ||
formState.discriptionMinLengthError
? classes.descriptionBoxError
: classes.descriptionBox
}
>
<Card className={classes.streamoffer}>
<InputLabel
htmlFor="outlined-stream-card"
fullwidth={true.toString()}
error={
formState.descriptionError ||
formState.discriptionMinLengthError
}
>
{genericConstants.DESCRIPTION}
</InputLabel>
<div className="rdw-root">
<Editor
id="description-editor"
editorState={editorState}
toolbarClassName="rdw-toolbar"
wrapperClassName="rdw-wrapper"
editorClassName="rdw-editor"
value={editorState}
onEditorStateChange={data => {
formState.descriptionError = false;
formState.discriptionMinLengthError = false;
setEditorState(data);
}}
/>
</div>
{formState.descriptionError ? (
<FormHelperText error={true}>
Description is required
</FormHelperText>
) : null}
{formState.discriptionMinLengthError ? (
<FormHelperText error={true}>
Description length should be less than 320
characters
</FormHelperText>
) : null}
</Card>
</Grid>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={6} xs={12}>
<CustomDateTimePicker
onChange={event => {
handleDateChange(dateFrom, event);
}}
value={formState.values[dateFrom] || null}
name={dateFrom}
label={get(ActivityFormSchema[dateFrom], "label")}
placeholder={get(
ActivityFormSchema[dateFrom],
"placeholder"
)}
fullWidth
error={hasError(dateFrom)}
helperText={
hasError(dateFrom)
? formState.errors[dateFrom].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
<Grid item md={6} xs={12}>
<CustomDateTimePicker
onChange={event => {
handleDateChange(dateTo, event);
}}
value={formState.values[dateTo] || null}
name={dateTo}
label={get(ActivityFormSchema[dateTo], "label")}
placeholder={get(
ActivityFormSchema[dateTo],
"placeholder"
)}
fullWidth
error={hasError(dateTo)}
helperText={
hasError(dateTo)
? formState.errors[dateTo].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12}>
<TextField
label="Address"
name="address"
value={formState.values["address"] || ""}
variant="outlined"
required
fullWidth
id="addressId"
onChange={handleChange}
error={hasError("address")}
helperText={
hasError("address")
? formState.errors["address"].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12}>
<Autocomplete
id="collegeId"
className={classes.root}
options={collegelist}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete("college", event, value);
}}
value={
collegelist[
collegelist.findIndex(function (item, i) {
return item.contact.id === formState.values.college;
})
] || null
}
renderInput={params => (
<TextField
{...params}
error={hasError("college")}
label="College"
variant="outlined"
required
name="tester"
helperText={
hasError("college")
? formState.errors["college"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12} className={classes.root}>
<Autocomplete
multiple={true}
id="collegeStreamID"
required
options={collegeStreamList}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleStreamChange("stream", event, value);
}}
value={stream}
filterSelectedOptions
renderInput={params => (
<TextField
{...params}
error={hasError("stream")}
label="Stream"
variant="outlined"
required
name="tester"
helperText={
hasError("stream")
? formState.errors["stream"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={3} className={classes.formgrid}>
<Grid item md={6} xs={12}>
<Autocomplete
id="educationYearId"
className={classes.root}
options={educationyearlist}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete("educationyear", event, value);
}}
value={
educationyearlist[
educationyearlist.findIndex(function (item, i) {
return item.id === formState.values.educationyear;
})
] || null
}
renderInput={params => (
<TextField
{...params}
error={hasError("educationyear")}
label="Education Year"
variant="outlined"
name="tester"
helperText={
hasError("educationyear")
? formState.errors["educationyear"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
{formState.editActivity ? (
<Grid item md={6} xs={12}>
<Autocomplete
id="combo-box-demo"
className={classes.root}
options={activityStatus}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete(
"activitystatus",
event,
value
);
}}
value={
activityStatus[
activityStatus.findIndex(function (item, i) {
return (
item.id === formState.values.activitystatus
);
})
] || null
}
renderInput={params => (
<TextField
{...params}
error={hasError("activitystatus")}
label="Activity Status"
variant="outlined"
name="tester"
helperText={
hasError("activitystatus")
? formState.errors["activitystatus"].map(
error => {
return error + " ";
}
)
: null
}
/>
)}
/>
</Grid>
) : null}
</Grid>
<Grid container spacing={3} className={classes.formgrid}>
<Grid item md={6} xs={12}>
<TextField
label="Trainer Name"
name="trainer"
id="trainerId"
value={formState.values["trainer"] || ""}
variant="outlined"
required
fullWidth
onChange={handleChange}
error={hasError("trainer")}
helperText={
hasError("trainer")
? formState.errors["trainer"].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
<Grid item md={6} xs={12}>
<Autocomplete
id="question_set"
className={classes.root}
options={questionSetData}
placeholder={"Select Question Set"}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete("questionSet", event, value);
}}
required
value={
questionSetData[
questionSetData.findIndex(function (item, i) {
return item.id === formState.values["questionSet"];
})
] || null
}
renderInput={params => (
<TextField
{...params}
label={"Question-Set"}
variant="outlined"
required
placeholder={"Select Question Set"}
error={hasError("questionSet")}
helperText={
hasError("questionSet")
? formState.errors["questionSet"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
</Grid>
</CardContent>
<Grid item xs={12} className={classes.CardActionGrid}>
<CardActions className={classes.btnspace}>
<Grid item xs={12}>
<Grid item xs={12} md={6} xl={3}>
{formState.editActivity ? (
<Grid container spacing={3}>
<Grid item md={2} xs={12}>
<YellowButton
color="primary"
type="submit"
mfullWidth
variant="contained"
style={{ marginRight: "18px" }}
onClick={handleSubmit}
>
<span>{genericConstants.SAVE_BUTTON_TEXT}</span>
</YellowButton>
</Grid>
<Grid item md={2} xs={12}>
<GrayButton
color="primary"
type="submit"
mfullWidth
variant="contained"
onClick={() => {
history.push(routeConstants.MANAGE_ACTIVITY);
}}
>
<span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
</GrayButton>
</Grid>
</Grid>
) : (
<Grid container spacing={3}>
<Grid item md={2} xs={12}>
<YellowButton
id="submitActivity"
color="primary"
type="submit"
mfullWidth
variant="contained"
style={{ marginRight: "18px" }}
onClick={handleSubmit}
>
<span>{genericConstants.SAVE_BUTTON_TEXT}</span>
</YellowButton>
</Grid>
<Grid item md={2} xs={12}>
<GrayButton
color="primary"
type="submit"
mfullWidth
variant="contained"
onClick={() => {
history.push(routeConstants.MANAGE_ACTIVITY);
}}
>
<span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
</GrayButton>
</Grid>
</Grid>
)}
</Grid>
</Grid>
</CardActions>
</Grid>
</form>
</Card>
</Grid>
<Backdrop className={classes.backDrop} open={backDrop}>
<CircularProgress color="inherit" />
</Backdrop>
</Grid>
);
}
Example #10
Source File: AddEditEvent.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
AddEditEvent = props => {
const [editorState, setEditorState] = React.useState(
EditorState.createEmpty()
);
const { setLoaderStatus } = useContext(LoaderContext);
const classes = useStyles();
const history = useHistory();
/** Initializiing form state value */
const [formState, setFormState] = useState({
isValid: false,
values: {
dateFrom: moment(),
dateTo: moment()
},
touched: {},
errors: {},
stateId: null,
setAllColleges: true,
isSuccess: false,
showPassword: false,
isEditEvent: props["editEvent"] ? props["editEvent"] : false,
dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
counter: 0,
files: {},
filess: {},
descriptionError: false,
discriptionMinLengthError: false,
dataToShowForCollegeMultiSelect: [],
eventCollegeIds: [],
dataToShowForStreamMultiSelect: [],
eventStreamsIds: [],
isCollegeAdminDoesNotHaveEditPreviliges: false,
deleteImage: false,
previewFile: {},
showPreviewImage: false,
showPreviewEditImage: false,
showPreviewNoImage: false,
showAddPreviewNoImage: true,
dynamicBar: [{ index: Math.random() }],
dynamicBarError: [],
dynamicEducationBar: [{ index: Math.random() }],
dynamicEducationBarError: [],
isCollegeAdmin:
auth.getUserInfo() !== null &&
auth.getUserInfo().role !== null &&
auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
? true
: false,
isStateClearFilter: false,
isContainDateValidation: true,
isDateValidated: false
});
const [collegeInfo] = useState({
college:
auth.getUserInfo() !== null &&
auth.getUserInfo().role !== null &&
auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
? auth.getUserInfo().studentInfo.organization
: {},
state:
auth.getUserInfo() !== null &&
auth.getUserInfo().role !== null &&
auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
? auth.getUserInfo().state
: {},
rpc:
auth.getUserInfo() !== null &&
auth.getUserInfo().role !== null &&
auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
? auth.getUserInfo().rpc
: {},
zone:
auth.getUserInfo() !== null &&
auth.getUserInfo().role !== null &&
auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
? auth.getUserInfo().zone
: {}
});
const [backdrop, setBackDrop] = useState(false);
const [states, setStates] = useState([]);
const [zones, setZones] = useState([]);
const [rpcs, setRpcs] = useState([]);
const [colleges, setColleges] = useState([]);
const [streams, setStreams] = useState(
props.streamOption ? props.streamOption : []
);
const inputLabel = React.useRef(null);
const [questionSetData, setQuestionSetData] = useState(
props.questionOption ? props.questionOption : []
);
const [qualifications, setQualifications] = useState([
{ id: 1, value: "secondary", name: "Secondary" },
{ id: 2, value: "graduation", name: "Graduation" },
{ id: 3, value: "senior_secondary", name: "Senior Secondary" },
{ id: 4, name: "Diploma", value: "diploma" },
{ id: 5, name: "ITI", value: "iti" },
// { id: 4, value: "undergraduate", name: "Undergraduate" },
{ id: 6, value: "postgraduate", name: "Postgraduate" },
{ id: 7, value: "other", name: "Other" }
]);
const [qualificationsDataBackup] = useState([
{ id: 1, value: "secondary", name: "Secondary" },
{ id: 2, value: "graduation", name: "Graduation" },
{ id: 3, value: "senior_secondary", name: "Senior Secondary" },
{ id: 4, name: "Diploma", value: "diploma" },
{ id: 5, name: "ITI", value: "iti" },
// { id: 4, value: "undergraduate", name: "Undergraduate" },
{ id: 6, value: "postgraduate", name: "Postgraduate" },
{ id: 7, value: "other", name: "Other" }
]);
const [educations, setEducations] = useState([
{ id: 1, value: "First" },
{ id: 2, value: "Second" },
{ id: 3, value: "Third" }
]);
const [educationsDataBackup] = useState([
{ id: 1, value: "First" },
{ id: 2, value: "Second" },
{ id: 3, value: "Third" }
]);
if (formState.isEditEvent && !formState.counter) {
setLoaderStatus(true);
/** Part for editing state */
if (props["dataForEdit"]) {
if (props["dataForEdit"]["title"]) {
formState.values[eventName] = props["dataForEdit"]["title"];
}
if (props["dataForEdit"]["description"]) {
formState.values[description] = props["dataForEdit"]["description"];
const blocksFromHtml = htmlToDraft(props["dataForEdit"]["description"]);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(
contentBlocks,
entityMap
);
const editorState = EditorState.createWithContent(contentState);
setEditorState(editorState);
}
if (props["dataForEdit"]["start_date_time"]) {
formState.values[dateFrom] = props["dataForEdit"]["start_date_time"];
//formState.defaultDate = date;
}
if (props["dataForEdit"]["end_date_time"]) {
formState.values[dateTo] = props["dataForEdit"]["end_date_time"];
}
if (props["dataForEdit"]["address"]) {
formState.values[address] = props["dataForEdit"]["address"];
}
if (props["dataForEdit"]["rpc"] && props["dataForEdit"]["rpc"]["id"]) {
formState.values[rpc] = props["dataForEdit"]["rpc"]["id"];
}
if (props["dataForEdit"]["zone"] && props["dataForEdit"]["zone"]["id"]) {
formState.values[zone] = props["dataForEdit"]["zone"]["id"];
}
if (
props["dataForEdit"]["question_set"] &&
props["dataForEdit"]["question_set"]["id"]
) {
formState.values[questionSet] =
props["dataForEdit"]["question_set"]["id"];
}
if (
props["dataForEdit"]["state"] &&
props["dataForEdit"]["state"]["id"]
) {
formState.values[state] = props["dataForEdit"]["state"]["id"];
}
if (
props["dataForEdit"] &&
props["dataForEdit"]["educations"] &&
props["dataForEdit"]["educations"].length
) {
let dynamicEducationBar = [];
for (let i in props["dataForEdit"]["educations"]) {
let tempEducationDynamicBarValue = {};
tempEducationDynamicBarValue["index"] = Math.random();
tempEducationDynamicBarValue["id"] =
props["dataForEdit"]["educations"][i]["id"];
tempEducationDynamicBarValue[education] =
props["dataForEdit"]["educations"][i]["education_year"];
tempEducationDynamicBarValue[educationpercentage] =
props["dataForEdit"]["educations"][i]["percentage"];
dynamicEducationBar.push(tempEducationDynamicBarValue);
}
formState.dynamicEducationBar = dynamicEducationBar;
}
if (
props["dataForEdit"] &&
props["dataForEdit"]["qualifications"] &&
props["dataForEdit"]["qualifications"].length
) {
let dynamicBar = [];
for (let i in props["dataForEdit"]["qualifications"]) {
let tempDynamicBarValue = {};
tempDynamicBarValue["index"] = Math.random();
tempDynamicBarValue["id"] =
props["dataForEdit"]["qualifications"][i]["id"];
tempDynamicBarValue[qualification] =
props["dataForEdit"]["qualifications"][i]["qualification"];
tempDynamicBarValue[percentage] =
props["dataForEdit"]["qualifications"][i]["percentage"];
dynamicBar.push(tempDynamicBarValue);
}
formState.dynamicBar = dynamicBar;
}
if (props["dataForEdit"] && props["dataForEdit"]["upload_logo"]) {
formState.showPreviewEditImage = true;
formState.showAddPreviewNoImage = false;
}
if (
props["dataForEdit"] &&
props["dataForEdit"]["upload_logo"] === null
) {
formState.showPreviewNoImage = true;
formState.showAddPreviewNoImage = true;
}
}
formState.counter += 1;
}
/** Use effect to populate Question Set */
useEffect(() => {
serviceProvider
.serviceProviderForGetRequest(QUESTION_SET)
.then(res => {
setQuestionSetData(res.data);
})
.catch(error => {});
}, []);
/** Streams data for Prepopulating */
const prePopulateStreamsData = streamsData => {
if (props["editEvent"]) {
if (
props["dataForEdit"]["streams"] &&
props["dataForEdit"]["streams"].length
) {
let array = [];
streamsData.map(stream => {
for (let i in props["dataForEdit"]["streams"]) {
if (props["dataForEdit"]["streams"][i]["id"] === stream["id"]) {
array.push(stream);
}
}
});
setFormState(formState => ({
...formState,
dataToShowForStreamMultiSelect: array
}));
let finalDataStream = [];
for (let i in props["dataForEdit"]["streams"]) {
finalDataStream.push(props["dataForEdit"]["streams"][i]["id"]);
}
formState.values[stream] = finalDataStream;
}
}
};
const prePopulateCollegeData = collegeData => {
if (props["editEvent"]) {
if (
props["dataForEdit"]["contacts"] &&
props["dataForEdit"]["contacts"].length
) {
let array = [];
collegeData.map(college => {
for (let i in props["dataForEdit"]["contacts"]) {
if (props["dataForEdit"]["contacts"][i]["id"] === college["id"]) {
array.push(college);
}
}
});
let setAllColleges = false;
if (collegeData.length === props["dataForEdit"]["contacts"].length) {
setAllColleges = true;
}
setFormState(formState => ({
...formState,
dataToShowForCollegeMultiSelect: array,
setAllColleges: setAllColleges
}));
let finalData = [];
for (let i in props["dataForEdit"]["contacts"]) {
finalData.push(props["dataForEdit"]["contacts"][i]["contact"]["id"]);
}
formState.values[college] = finalData;
}
} else {
let collegeArrayToSet = [];
collegeData.map(c => {
collegeArrayToSet.push(c.id);
});
setFormState(formState => ({
...formState,
values: {
...formState.values,
[college]: collegeArrayToSet
},
dataToShowForCollegeMultiSelect: collegeData
}));
}
};
/** Setting educations and qualifications */
useEffect(() => {
setLoaderStatus(true);
let paramsForPageSize = {
pageSize: -1
};
if (formState.isCollegeAdmin) {
setStates([collegeInfo.state]);
} else {
serviceProvider
.serviceProviderForGetRequest(STATES_URL, paramsForPageSize)
.then(res => {
res.data.result.map(s => {
if (s.name === "Uttar Pradesh") {
formState.stateId = s.id;
}
});
setStates(res.data.result);
})
.catch(error => {
console.log("error", error);
});
}
let educationDataForEdit = [
{ id: 1, value: "First" },
{ id: 2, value: "Second" },
{ id: 3, value: "Third" }
];
if (formState.isEditEvent) {
let tempEducationData = educationDataForEdit;
let educationPercentageArray = props["dataForEdit"]["educations"];
for (let i in educationPercentageArray) {
let id = educationPercentageArray[i]["education_year"];
for (let j in tempEducationData) {
if (tempEducationData[j]["value"] === id)
tempEducationData.splice(j, 1);
}
}
setEducations(tempEducationData);
}
let dataForEditing = [
{ id: 1, value: "secondary", name: "Secondary" },
{ id: 2, value: "graduation", name: "Graduation" },
{ id: 3, value: "senior_secondary", name: "Senior Secondary" },
{ id: 4, value: "undergraduate", name: "Undergraduate" },
{ id: 5, value: "postgraduate", name: "Postgraduate" },
{ id: 6, value: "other", name: "Other" }
];
if (formState.isEditEvent) {
let tempQualificationData = dataForEditing;
let qualificationPercentageArray = props["dataForEdit"]["qualifications"];
for (let i in qualificationPercentageArray) {
let id = qualificationPercentageArray[i]["qualification"];
for (let j in tempQualificationData) {
if (tempQualificationData[j]["value"] === id)
tempQualificationData.splice(j, 1);
}
}
setQualifications(tempQualificationData);
}
if (!formState.isCollegeAdmin) {
serviceProvider
.serviceProviderForGetRequest(STREAM_URL, paramsForPageSize)
.then(res => {
setStreams(res.data.result);
prePopulateStreamsData(res.data.result);
})
.catch(error => {
console.log("errorstream", error);
});
} else if (formState.isCollegeAdmin) {
let streamData = [];
auth.getUserInfo().studentInfo.organization.stream_strength.map(data => {
streamData.push(data["stream"]);
});
setStreams(streamData);
prePopulateStreamsData(streamData);
}
setLoaderStatus(false);
}, []);
/** Setting rpc, zone on state change */
useEffect(() => {
if (
formState.values.hasOwnProperty(state) &&
formState.values[state] !== null &&
formState.values[state] !== undefined
) {
fetchZoneRpcData();
}
}, [formState.values[state]]);
/** Common function to get zones, rpcs after changing state */
async function fetchZoneRpcData() {
setLoaderStatus(true);
if (
formState.values.hasOwnProperty(state) &&
formState.values[state] !== null &&
formState.values[state] !== undefined &&
formState.values[state] !== ""
) {
let zones_url =
STATES_URL +
"/" +
formState.values[state] +
"/" +
strapiApiConstants.STRAPI_ZONES;
if (!formState.isCollegeAdmin) {
await serviceProvider
.serviceProviderForGetRequest(zones_url)
.then(res => {
setZones(res.data.result);
})
.catch(error => {
console.log("error", error);
});
} else if (formState.isCollegeAdmin) {
setZones([collegeInfo.zone]);
}
let rpcs_url =
STATES_URL +
"/" +
formState.values[state] +
"/" +
strapiApiConstants.STRAPI_RPCS;
if (!formState.isCollegeAdmin) {
await serviceProvider
.serviceProviderForGetRequest(rpcs_url)
.then(res => {
if (Array.isArray(res.data)) {
setRpcs(res.data[0].result);
} else {
setRpcs(res.data.result);
}
})
.catch(error => {
console.log("error", error);
});
} else if (formState.isCollegeAdmin) {
setRpcs([collegeInfo.rpc]);
}
}
setLoaderStatus(false);
}
useEffect(() => {}, []);
useEffect(() => {
fetchCollegeData();
}, []);
/** Function to get college data after selcting zones and rpc's */
async function fetchCollegeData() {
setLoaderStatus(true);
let params = {
pageSize: -1
};
if (!formState.isCollegeAdmin) {
await serviceProvider
.serviceProviderForGetRequest(COLLEGE_URL, params)
.then(res => {
setColleges(res.data.result);
prePopulateCollegeData(res.data.result);
})
.catch(error => {
console.log("error", error);
});
} else if (formState.isCollegeAdmin) {
setColleges([collegeInfo.college]);
prePopulateCollegeData([collegeInfo.college]);
}
setLoaderStatus(false);
}
const hasError = field => (formState.errors[field] ? true : false);
const handleChange = e => {
e.persist();
setFormState(formState => ({
...formState,
values: {
...formState.values,
[e.target.name]:
e.target.type === "checkbox" ? e.target.checked : e.target.value
},
touched: {
...formState.touched,
[e.target.name]: true
}
}));
if (formState.errors.hasOwnProperty(e.target.name)) {
delete formState.errors[e.target.name];
}
};
const checkErrorInDynamicBar = (field, currentDynamicBarValue) => {
if (field === "qualification" || field === "percentage") {
let errorData = { error: false, value: "" };
if (formState.dynamicBarError.length) {
formState.dynamicBarError.map(barErrorValue => {
if (barErrorValue["index"] === currentDynamicBarValue["index"]) {
if (barErrorValue.hasOwnProperty(field)) {
errorData.error = true;
errorData.value = barErrorValue[field];
}
}
});
}
return errorData;
} else if (field === "education" || field === "educationpercentage") {
let errorEducationData = { error: false, value: "" };
if (formState.dynamicEducationBarError.length) {
formState.dynamicEducationBarError.map(barErrorValue => {
if (barErrorValue["index"] === currentDynamicBarValue["index"]) {
if (barErrorValue.hasOwnProperty(field)) {
errorEducationData.error = true;
errorEducationData.value = barErrorValue[field];
}
}
});
}
return errorEducationData;
}
};
/** Adding a new row in dynamic bar */
const addNewRow = (e, extendBarName) => {
e.persist();
if (extendBarName === "qualification") {
setFormState(formState => ({
...formState,
dynamicBar: [...formState.dynamicBar, { index: Math.random() }]
}));
} else if (extendBarName === "education") {
setFormState(formState => ({
...formState,
dynamicEducationBar: [
...formState.dynamicEducationBar,
{ index: Math.random() }
]
}));
}
};
/** To delete a value from dynamic bar */
const clickOnDelete = (record, index) => {
setFormState(formState => ({
...formState,
dynamicBar: formState.dynamicBar.filter(r => r !== record)
}));
setFormState(formState => ({
...formState,
dynamicEducationBar: formState.dynamicEducationBar.filter(
r => r !== record
)
}));
if (record[qualification]) {
let qualificationsTempArray = [];
qualificationsTempArray = qualifications;
qualificationsDataBackup.map(qualificationData => {
if (record["qualification"] === qualificationData["value"]) {
qualificationsTempArray.push(qualificationData);
}
});
setQualifications(qualificationsTempArray);
}
if (record[education]) {
let qualificationsTempArray = [];
qualificationsTempArray = educations;
educationsDataBackup.map(qualificationData => {
if (record["education"] === qualificationData["value"]) {
qualificationsTempArray.push(qualificationData);
}
});
setEducations(qualificationsTempArray);
}
};
/** Handling multi select values for dynamic bar */
const handleChangeForDynamicGrid = (
eventName,
event,
selectedValueForAutoComplete,
dynamicGridValue,
isAutoComplete,
isTextBox
) => {
event.persist();
if (eventName === "qualification" || eventName === "percentage") {
/**TO SET VALUES OF AUTOCOMPLETE */
if (isAutoComplete) {
if (selectedValueForAutoComplete !== null) {
setFormState(formState => ({
...formState,
dynamicBar: formState.dynamicBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
let qualificationsTempArray = [];
qualifications.map(qualificationData => {
if (
qualificationData["id"] !==
selectedValueForAutoComplete["id"]
) {
qualificationsTempArray.push(qualificationData);
}
});
setQualifications(qualificationsTempArray);
r["id"] = selectedValueForAutoComplete["id"];
r[eventName] = selectedValueForAutoComplete["value"];
return r;
} else {
return r;
}
})
}));
} else {
/** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
setFormState(formState => ({
...formState,
dynamicBar: formState.dynamicBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
let qualificationsTempArray = [];
qualificationsTempArray = qualifications;
qualificationsDataBackup.map(qualificationData => {
if (r[eventName] === qualificationData["value"]) {
qualificationsTempArray.push(qualificationData);
}
});
setQualifications(qualificationsTempArray);
delete r[eventName];
return r;
} else {
return r;
}
})
}));
}
}
if (isTextBox) {
if (
event.target.value === "" ||
regexForPercentage.test(event.target.value)
) {
if (event.target.value.length <= 2) {
setFormState(formState => ({
...formState,
dynamicBar: formState.dynamicBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
r[eventName] = event.target.value;
if (r[eventName] === "") {
delete r[eventName];
}
return r;
} else {
return r;
}
})
}));
}
}
}
/** Clear errors if any */
formState.dynamicBarError.map(errorValues => {
if (errorValues["index"] === dynamicGridValue["index"]) {
delete errorValues[eventName];
}
});
} else if (
eventName === "education" ||
eventName === "educationpercentage"
) {
if (isAutoComplete) {
if (selectedValueForAutoComplete !== null) {
setFormState(formState => ({
...formState,
dynamicEducationBar: formState.dynamicEducationBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
let educationsTempArray = [];
educations.map(educationData => {
if (
educationData["id"] !== selectedValueForAutoComplete["id"]
) {
educationsTempArray.push(educationData);
}
});
setEducations(educationsTempArray);
r["id"] = selectedValueForAutoComplete["id"];
r[eventName] = selectedValueForAutoComplete["value"];
return r;
} else {
return r;
}
})
}));
} else {
/** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
setFormState(formState => ({
...formState,
dynamicEducationBar: formState.dynamicEducationBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
let educationsTempArray = [];
educationsTempArray = educations;
educationsDataBackup.map(educationData => {
if (r[eventName] === educationData["value"]) {
educationsTempArray.push(educationData);
}
});
setQualifications(educationsTempArray);
delete r[eventName];
return r;
} else {
return r;
}
})
}));
}
}
if (isTextBox) {
if (
event.target.value === "" ||
regexForPercentage.test(event.target.value)
) {
if (event.target.value.length <= 2) {
setFormState(formState => ({
...formState,
dynamicEducationBar: formState.dynamicEducationBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
r[eventName] = event.target.value;
if (r[eventName] === "") {
delete r[eventName];
}
return r;
} else {
return r;
}
})
}));
}
}
}
/** Clear errors if any */
formState.dynamicBarError.map(errorValues => {
if (errorValues["index"] === dynamicGridValue["index"]) {
delete errorValues[eventName];
}
});
}
};
/** Validate DynamicGrid */
const validateDynamicGridValues = () => {
let validationCounter = 0;
/** Empty the error array of dynamic bar */
formState.dynamicBarError = [];
formState.dynamicBar.map(value => {
let valueToPutInDynmicBarError = {};
valueToPutInDynmicBarError["index"] = value["index"];
/** Validate dynamikc bar */
if (
value.hasOwnProperty(qualification) &&
!value.hasOwnProperty(percentage)
) {
valueToPutInDynmicBarError[percentage] =
"Percentage is required as Qualification is present";
validationCounter += 1;
} else if (
value.hasOwnProperty(percentage) &&
!value.hasOwnProperty(qualification)
) {
valueToPutInDynmicBarError[qualification] =
"Qualification is required as percentage is present";
validationCounter += 1;
}
formState.dynamicBarError.push(valueToPutInDynmicBarError);
});
formState.dynamicEducationBarError = [];
formState.dynamicEducationBar.map(value => {
let valueToPutInDynmicBarError = {};
valueToPutInDynmicBarError["index"] = value["index"];
/** Validate dynamikc bar */
if (
value.hasOwnProperty(education) &&
!value.hasOwnProperty(educationpercentage)
) {
valueToPutInDynmicBarError[educationpercentage] =
"Percentage is required as Education is present";
validationCounter += 1;
} else if (
value.hasOwnProperty(educationpercentage) &&
!value.hasOwnProperty(education)
) {
valueToPutInDynmicBarError[education] =
"Education is required as percentage is present";
validationCounter += 1;
}
formState.dynamicEducationBarError.push(valueToPutInDynmicBarError);
});
if (validationCounter > 0) {
return false;
} else {
return true;
}
};
const getDynamicBarData = () => {
let qualificationsPercentageArrayValues = [];
formState.dynamicBar.map(field => {
let qualificationPercentageValue = {};
if (
field.hasOwnProperty(qualification) &&
field.hasOwnProperty(percentage)
) {
qualificationPercentageValue["qualification"] = field[qualification];
qualificationPercentageValue["percentage"] = parseInt(
field[percentage]
);
qualificationsPercentageArrayValues.push(qualificationPercentageValue);
}
});
return qualificationsPercentageArrayValues;
};
const getDynamicEducationData = () => {
let educationsPercentageArrayValues = [];
formState.dynamicEducationBar.map(field => {
let educationPercentageValue = {};
if (
field.hasOwnProperty(education) &&
field.hasOwnProperty(educationpercentage)
) {
educationPercentageValue["education_year"] = field[education];
educationPercentageValue["percentage"] = parseInt(
field[educationpercentage]
);
educationsPercentageArrayValues.push(educationPercentageValue);
}
});
return educationsPercentageArrayValues;
};
/** Handle change for autocomplete fields */
const handleChangeAutoComplete = (eventName, event, value) => {
/**TO SET VALUES OF AUTOCOMPLETE */
if (formState.errors.hasOwnProperty(eventName)) {
delete formState.errors[eventName];
}
if (value !== null) {
setFormState(formState => ({
...formState,
values: {
...formState.values,
[eventName]: value.id
},
touched: {
...formState.touched,
[eventName]: true
},
isStateClearFilter: false
}));
} else {
let setStateFilterValue = false;
/** If we click cross for state the zone and rpc should clear off! */
if (eventName === state) {
/**
This flag is used to determine that state is cleared which clears
off zone and rpc by setting their value to null
*/
setStateFilterValue = true;
/**
When state is cleared then clear rpc and zone
*/
setRpcs([]);
setZones([]);
setColleges([]);
// setStreams([]);
delete formState.values[zone];
delete formState.values[rpc];
formState.dataToShowForCollegeMultiSelect = [];
} else if (eventName === rpc || eventName === zone) {
setColleges([]);
formState.dataToShowForCollegeMultiSelect = [];
}
setFormState(formState => ({
...formState,
isStateClearFilter: setStateFilterValue
}));
/** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
delete formState.values[eventName];
}
};
const handleCheckBox = event => {
/** If the checkbox is checked */
if (!formState.setAllColleges) {
/** Delete current value */
delete formState.values[college];
/** Set validations */
EventSchema.college.required = false;
EventSchema.college.validations = {};
/** Delete if errors present */
delete formState.errors[college];
/** Set college list when all collgees check box is checked */
let collegeArrayToSet = [];
colleges.map(c => {
collegeArrayToSet.push(c.id);
});
setFormState(formState => ({
...formState,
setAllColleges: !formState.setAllColleges,
values: {
...formState.values,
[college]: collegeArrayToSet
},
dataToShowForCollegeMultiSelect: colleges
}));
} else {
delete formState.values[college];
EventSchema.college.required = true;
EventSchema.college.validations = {
required: {
value: "true",
message: "College is required"
}
};
/** Delete if errors present */
delete formState.errors[college];
setFormState(formState => ({
...formState,
setAllColleges: !formState.setAllColleges,
dataToShowForCollegeMultiSelect: []
}));
}
};
const handleSubmit = event => {
event.preventDefault();
setBackDrop(true);
let isValid = false;
if (formState.isCollegeAdmin && !formState.isEditEvent) {
setDataForCollegeAdmin();
} else {
formState.values[state] = formState.stateId;
}
/** Validate DynamicGrid */
let isDynamicBarValid;
/** Check validity of dynamic bar */
isDynamicBarValid = validateDynamicGridValues();
let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
formState.values,
EventSchema
);
if (checkAllFieldsValid) {
/** Evaluated only if all keys are valid inside formstate */
formState.errors = formUtilities.setErrors(
formState.values,
EventSchema,
true,
dateFrom,
dateTo
);
/** Check date validation */
if (formUtilities.checkEmpty(formState.errors)) {
isValid = true;
}
/** */
} else {
/** This is used to find out which all required fields are not filled */
formState.values = formUtilities.getListOfKeysNotPresent(
formState.values,
EventSchema
);
formState.errors = formUtilities.setErrors(
formState.values,
EventSchema,
true,
dateFrom,
dateTo
);
}
formState.descriptionError = false;
if (
convertToRaw(editorState.getCurrentContent()).blocks &&
convertToRaw(editorState.getCurrentContent()).blocks.length
) {
let arrayToCheckIn = convertToRaw(editorState.getCurrentContent()).blocks;
let validationCounter = 0;
let validationMinCounter = 0;
for (let i in arrayToCheckIn) {
if (
arrayToCheckIn[i]["text"] &&
arrayToCheckIn[i]["text"].trim().length !== 0
) {
validationCounter += 1;
break;
}
}
if (validationCounter === 0) {
formState.descriptionError = true;
}
for (let i in arrayToCheckIn) {
if (
arrayToCheckIn[i]["text"] &&
arrayToCheckIn[i]["text"].trim().length > 320
) {
validationMinCounter += 1;
break;
}
}
if (validationMinCounter !== 0) {
formState.discriptionMinLengthError = true;
}
}
if (
isValid &&
!formState.descriptionError &&
!formState.discriptionMinLengthError &&
isDynamicBarValid
) {
/** CALL POST FUNCTION */
postEventData();
/** Call axios from here */
setFormState(formState => ({
...formState,
isValid: true
}));
} else {
setFormState(formState => ({
...formState,
isValid: false
}));
setBackDrop(false);
}
};
const setDataForCollegeAdmin = () => {
formState.values[zone] = collegeInfo.zone.id;
formState.values[rpc] = collegeInfo.rpc.id;
formState.values[college] = [collegeInfo.college.contact.id];
formState.values[state] = collegeInfo.state.id;
};
const postEventData = () => {
/** Setting quaalifications */
let qualificationPercentageArray = [];
qualificationPercentageArray = getDynamicBarData();
/** Setting educations */
let educationPercentageArray = [];
educationPercentageArray = getDynamicEducationData();
/** Data to post */
let postData = databaseUtilities.addEvent(
formState.values[eventName],
draftToHtml(convertToRaw(editorState.getCurrentContent())),
formState.values[dateFrom],
formState.values[dateTo],
formState.values[address],
formState.values[zone] ? formState.values[zone] : null,
formState.values[rpc] ? formState.values[rpc] : null,
qualificationPercentageArray,
educationPercentageArray,
formState.values[college] ? formState.values[college] : null,
formState.values[stream] ? formState.values[stream] : null,
formState.values[state] ? formState.values[state] : null,
formState.values[questionSet] ? formState.values[questionSet] : null
);
if (formState.isEditEvent) {
serviceProvider
.serviceProviderForPutRequest(
EVENTS_URL,
formState.dataForEdit["id"],
postData
)
.then(res => {
if (formState.files.name) {
postImage(res.data.id);
} else {
history.push({
pathname: routeConstants.MANAGE_EVENT,
fromeditEvent: true,
isDataEdited: true,
editedEventData: res.data,
addResponseMessage: "",
editedData: {}
});
}
setBackDrop(false);
})
.catch(error => {
console.log("puterror", error);
history.push({
pathname: routeConstants.MANAGE_EVENT,
fromeditEvent: true,
isDataEdited: false,
editResponseMessage: "",
editedData: {}
});
setBackDrop(false);
});
} else {
serviceProvider
.serviceProviderForPostRequest(EVENTS_URL, postData)
.then(res => {
if (formState.files.name) {
postImage(res.data.id);
} else {
history.push({
pathname: routeConstants.MANAGE_EVENT,
fromAddEvent: true,
isDataAdded: true,
addedEventData: res.data,
addResponseMessage: "",
addedData: {}
});
}
setBackDrop(false);
})
.catch(error => {
console.log("posterror", error);
history.push({
pathname: routeConstants.MANAGE_EVENT,
fromeditEvent: true,
isDataEdited: false,
editResponseMessage: "",
editedData: {}
});
setBackDrop(false);
});
}
};
const postImage = id => {
let postImageData = databaseUtilities.uploadDocument(
formState.files,
ref,
id,
field
);
serviceProvider
.serviceProviderForPostRequest(DOCUMENT_URL, postImageData)
.then(res => {
history.push({
pathname: routeConstants.MANAGE_EVENT,
fromAddEvent: true,
isDataAdded: true,
addResponseMessage: "",
addedData: {}
});
})
.catch(err => {
console.log("error", err);
});
};
const handleFileChange = event => {
event.persist();
setFormState(formState => ({
...formState,
values: {
...formState.values,
[event.target.name]: event.target.value
},
touched: {
...formState.touched,
[event.target.name]: true
},
files: event.target.files[0],
previewFile: URL.createObjectURL(event.target.files[0]),
showPreviewEditImage: false,
showPreviewNoImage: false,
showPreviewImage: true,
showAddPreviewNoImage: false
}));
/** This is used to remove any existing errors if present in text field */
if (formState.errors.hasOwnProperty(event.target.name)) {
delete formState.errors[event.target.name];
}
};
const handleDateChange = (dateObject, event) => {
if (formState.errors.hasOwnProperty(dateObject)) {
delete formState.errors[dateObject];
}
setFormState(formState => ({
...formState,
values: {
...formState.values,
[dateObject]: event
},
touched: {
...formState.touched,
[dateObject]: true
},
isStateClearFilter: false
}));
};
const handleMultiSelectChange = (eventName, event, value) => {
let multiarray = [];
delete formState.errors[eventName];
if (eventName === college) {
formState.dataToShowForCollegeMultiSelect = value;
for (var i = 0; i < value.length; i++) {
multiarray.push(value[i]["contact"].id);
}
}
if (eventName === stream) {
formState.dataToShowForStreamMultiSelect = value;
for (var i = 0; i < value.length; i++) {
multiarray.push(value[i].id);
}
}
if (value !== null) {
setFormState(formState => ({
...formState,
values: {
...formState.values,
[eventName]: multiarray
},
touched: {
...formState.touched,
[eventName]: true
},
isStateClearFilter: false
}));
} else {
delete formState.values[eventName];
}
};
return (
<Grid>
<Grid item xs={12} className={classes.title}>
<Typography variant="h4" gutterBottom>
{props["editEvent"] ? "Edit Event" : genericConstants.ADD_EVENT_TEXT}
</Typography>
</Grid>
<Grid spacing={3}>
<Card>
<form autoComplete="off" noValidate onSubmit={handleSubmit} id="form">
<CardContent>
<Grid item xs={12} md={6} xl={3}>
<Grid container className={classes.formgridInputFile}>
<Grid item md={10} xs={12}>
<div className={classes.imageDiv}>
{
formState.showPreviewImage ? (
<Img
src={formState.previewFile}
alt="abc"
loader={<Spinner />}
className={classes.UploadImage}
/>
) : null
// <div class={classes.DefaultNoImage}></div>
}
{formState.showPreviewEditImage &&
formState.dataForEdit["upload_logo"] !== null &&
formState.dataForEdit["upload_logo"] !== undefined &&
formState.dataForEdit["upload_logo"] !== {} ? (
<Img
src={
strapiApiConstants.STRAPI_DB_URL_WITHOUT_HASH +
formState.dataForEdit["upload_logo"]["url"]
}
loader={<Spinner />}
className={classes.UploadImage}
/>
) : null}
{formState.showPreviewNoImage ? (
<Img
src={"../"}
loader={<Spinner />}
className={classes.UploadImage}
/>
) : null}
{formState.showAddPreviewNoImage ? (
<div className={classes.DefaultNoImage}></div>
) : null}
</div>
</Grid>
</Grid>
<Grid container className={classes.MarginBottom}>
<Grid item md={10} xs={12}>
<TextField
fullWidth
id={get(EventSchema[files], "id")}
name={files}
onChange={handleFileChange}
required
type={get(EventSchema[files], "type")}
value={formState.values[files] || ""}
error={hasError(files)}
inputProps={{ accept: "image/*" }}
helperText={
hasError(files)
? formState.errors[files].map(error => {
return error + " ";
})
: null
}
variant="outlined"
className={classes.inputFile}
/>
<label htmlFor={get(EventSchema[files], "id")}>
<Button
variant="contained"
color="primary"
component="span"
fullWidth
className={classes.InputFileButton}
startIcon={<AddOutlinedIcon />}
>
ADD NEW EVENT LOGO
</Button>
</label>
</Grid>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={3} className={classes.formgrid}>
<Grid item md={12} xs={12}>
<TextField
label={get(EventSchema[eventName], "label")}
id={get(EventSchema[eventName], "id")}
name={eventName}
placeholder={get(EventSchema[eventName], "placeholder")}
value={formState.values[eventName] || ""}
error={hasError(eventName)}
variant="outlined"
required
fullWidth
onChange={handleChange}
helperText={
hasError(eventName)
? formState.errors[eventName].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12} className={"descriptionBox"}>
<Grid
className={
formState.descriptionError ||
formState.discriptionMinLengthError
? classes.descriptionBoxError
: classes.descriptionBox
}
>
<Card className={classes.streamoffer}>
<InputLabel
htmlFor="outlined-stream-card"
fullwidth={true.toString()}
error={
formState.descriptionError ||
formState.discriptionMinLengthError
}
>
{genericConstants.DESCRIPTION}
</InputLabel>
<div className="rdw-root">
<Editor
editorState={editorState}
toolbarClassName="rdw-toolbar"
wrapperClassName="rdw-wrapper"
editorClassName="rdw-editor"
onEditorStateChange={data => {
formState.descriptionError = false;
formState.discriptionMinLengthError = false;
setEditorState(data);
}}
/>
</div>
{formState.descriptionError ? (
<FormHelperText error={true}>
Description is required
</FormHelperText>
) : null}
{formState.discriptionMinLengthError ? (
<FormHelperText error={true}>
Description length should be less than 320
characters
</FormHelperText>
) : null}
</Card>
</Grid>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={6} xs={12}>
<CustomDateTimePicker
id={get(EventSchema[dateFrom], "id")}
onChange={event => {
handleDateChange(dateFrom, event);
}}
value={formState.values[dateFrom] || null}
name={dateFrom}
label={get(EventSchema[dateFrom], "label")}
placeholder={get(EventSchema[dateFrom], "placeholder")}
fullWidth
error={hasError(dateFrom)}
helperText={
hasError(dateFrom)
? formState.errors[dateFrom].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
<Grid item md={6} xs={12}>
<CustomDateTimePicker
id={get(EventSchema[dateTo], "id")}
onChange={event => {
handleDateChange(dateTo, event);
}}
value={formState.values[dateTo] || null}
name={dateTo}
label={get(EventSchema[dateTo], "label")}
placeholder={get(EventSchema[dateTo], "placeholder")}
fullWidth
error={hasError(dateTo)}
helperText={
hasError(dateTo)
? formState.errors[dateTo].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12}>
<TextField
label={get(EventSchema[address], "label")}
id={get(EventSchema[address], "id")}
name={address}
placeholder={get(EventSchema[address], "placeholder")}
value={formState.values[address] || ""}
error={hasError(address)}
variant="outlined"
required
multiline
fullWidth
onChange={handleChange}
helperText={
hasError(address)
? formState.errors[address].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
</Grid>
<Grid
container
spacing={3}
className={classes.MarginBottom}
></Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
{!formState.isCollegeAdmin ? (
<Grid item md={12} xs={12}>
<FormControlLabel
control={
<Checkbox
checked={formState.setAllColleges}
onChange={handleCheckBox}
name="selectAllColleges"
color="yellow"
/>
}
label="Select All Colleges"
/>
</Grid>
) : null}
<Grid item md={12} xs={12}>
{formState.isCollegeAdmin && !formState.isEditEvent ? (
<ReadOnlyTextField
id={get(EventSchema[college], "id")}
label={get(EventSchema[college], "label")}
defaultValue={collegeInfo.college.name}
/>
) : (
<Autocomplete
id={get(EventSchema[college], "id")}
multiple
limitTags={2}
options={colleges}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleMultiSelectChange(college, event, value);
}}
filterSelectedOptions
name={college}
disabled={
(formState.isCollegeAdmin && formState.isEditEvent) ||
formState.setAllColleges
? true
: false
}
value={
formState.dataToShowForCollegeMultiSelect || null
}
renderInput={params => (
<TextField
{...params}
error={hasError(college)}
helperText={
hasError(college)
? formState.errors[college].map(error => {
return error + " ";
})
: null
}
placeholder={get(
EventSchema[college],
"placeholder"
)}
value={option => option.id}
name={college}
key={option => option.id}
label={get(EventSchema[college], "label")}
variant="outlined"
/>
)}
/>
)}
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={6} xs={12}>
<Autocomplete
id={get(EventSchema[stream], "id")}
multiple
options={streams}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleMultiSelectChange(stream, event, value);
}}
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
filterSelectedOptions
name={stream}
value={formState.dataToShowForStreamMultiSelect || null}
renderInput={params => (
<TextField
{...params}
error={hasError(stream)}
helperText={
hasError(stream)
? formState.errors[stream].map(error => {
return error + " ";
})
: null
}
placeholder={get(EventSchema[stream], "placeholder")}
value={option => option.id}
name={stream}
key={option => option.id}
label={get(EventSchema[stream], "label")}
variant="outlined"
/>
)}
/>
</Grid>
<Grid item md={6} xs={12}>
<Autocomplete
id={get(EventSchema[questionSet], "id")}
className={classes.root}
options={questionSetData}
placeholder={get(EventSchema[questionSet], "placeholder")}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete(questionSet, event, value);
}}
value={
questionSetData[
questionSetData.findIndex(function (item, i) {
return item.id === formState.values[questionSet];
})
] || null
}
renderInput={params => (
<TextField
{...params}
label={get(EventSchema[questionSet], "label")}
variant="outlined"
placeholder={get(
EventSchema[questionSet],
"placeholder"
)}
error={hasError(questionSet)}
helperText={
hasError(questionSet)
? formState.errors[questionSet].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={1} className={classes.formgrid}>
<Grid item md={12} xs={12} className={classes.streamcard}>
<Card className={classes.streamoffer}>
<InputLabel
htmlFor="outlined-stream-card"
fullwidth={true.toString()}
>
{genericConstants.QUALIFICATIONANDPERCENTAGE}
</InputLabel>
{formState.dynamicBar.map((val, idx) => {
let qualificationId = `qualification-${idx}`,
percentageId = `percentage-${idx}`;
return (
<Card
id="outlined-stream-card"
fullwidth={true.toString()}
className={classes.streamcardcontent}
key={idx}
>
<CardContent>
<Grid container spacing={1}>
<Grid item xs={5}>
<FormControl
variant="outlined"
fullWidth
className={classes.formControl}
>
<InputLabel
ref={inputLabel}
id="demo-simple-select-outlined-label"
></InputLabel>
<Autocomplete
id={qualificationId}
options={qualifications}
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeForDynamicGrid(
qualification,
event,
value,
val,
true,
false
);
}}
data-id={idx}
name={qualificationId}
value={
qualificationsDataBackup[
qualificationsDataBackup.findIndex(
function (item, i) {
return (
item.value ===
formState.dynamicBar[idx][
qualification
]
);
}
)
] || null
}
renderInput={params => (
<TextField
{...params}
value={option => option.id}
name={qualificationId}
error={
checkErrorInDynamicBar(
qualification,
val
)["error"]
}
helperText={
checkErrorInDynamicBar(
qualification,
val
)["error"]
? checkErrorInDynamicBar(
qualification,
val
)["value"]
: null
}
placeholder={get(
EventSchema[qualification],
"placeholder"
)}
key={option => option.id}
label={get(
EventSchema[qualification],
"label"
)}
variant="outlined"
/>
)}
/>
</FormControl>
</Grid>
<Grid item xs={5}>
<TextField
label="Percentage"
name={percentageId}
variant="outlined"
fullWidth
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
data-id={idx}
id={percentageId}
value={
formState.dynamicBar[idx][percentage] ||
""
}
error={
checkErrorInDynamicBar(percentage, val)[
"error"
]
}
helperText={
checkErrorInDynamicBar(percentage, val)[
"error"
]
? checkErrorInDynamicBar(
percentage,
val
)["value"]
: null
}
placeholder={get(
EventSchema[percentage],
"placeholder"
)}
onChange={event => {
handleChangeForDynamicGrid(
percentage,
event,
null,
val,
false,
true
);
}}
/>
</Grid>
<Grid item xs={2}>
{idx > 0 ? (
<DeleteForeverOutlinedIcon
onClick={e =>
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? null
: clickOnDelete(val, idx)
}
style={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? { color: "gray", fontSize: "24px" }
: { color: "red", fontSize: "24px" }
}
/>
) : (
""
)}
</Grid>
</Grid>
</CardContent>
</Card>
);
})}
<div className={classes.btnspaceadd}>
<Grid item xs={12} md={3} lg={3} xl={3}>
<YellowButton
type="button"
color="primary"
variant="contained"
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: qualifications.length
? false
: true
}
className={classes.add_more_btn}
onClick={e => {
addNewRow(e, qualification);
}}
>
{genericConstants.ADD_MORE_TEXT}
</YellowButton>
</Grid>
</div>
</Card>
</Grid>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={1} className={classes.formgrid}>
<Grid item md={12} xs={12} className={classes.streamcard}>
<Card className={classes.streamoffer}>
<InputLabel
htmlFor="outlined-stream-card"
fullwidth={true.toString()}
>
{genericConstants.EDUCATIONANDPERCENTAGE}
</InputLabel>
{formState.dynamicEducationBar.map((val, idx) => {
let qualificationId = `education-${idx}`,
percentageId = `percentage-${idx}`;
return (
<Card
id="outlined-stream-card"
fullwidth={true.toString()}
className={classes.streamcardcontent}
key={idx}
>
<CardContent>
<Grid container spacing={1}>
<Grid item xs={5}>
<FormControl
variant="outlined"
fullWidth
className={classes.formControl}
>
<InputLabel
ref={inputLabel}
id="demo-simple-select-outlined-label"
></InputLabel>
<Autocomplete
id={qualificationId}
options={educations}
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
getOptionLabel={option => option.value}
onChange={(event, value) => {
handleChangeForDynamicGrid(
education,
event,
value,
val,
true,
false
);
}}
data-id={idx}
name={qualificationId}
value={
educationsDataBackup[
educationsDataBackup.findIndex(
function (item, i) {
return (
item.value ===
formState.dynamicEducationBar[
idx
][education]
);
}
)
] || null
}
renderInput={params => (
<TextField
{...params}
value={option => option.id}
name={qualificationId}
error={
checkErrorInDynamicBar(
education,
val
)["error"]
}
helperText={
checkErrorInDynamicBar(
education,
val
)["error"]
? checkErrorInDynamicBar(
education,
val
)["value"]
: null
}
placeholder={get(
EventSchema[education],
"placeholder"
)}
key={option => option.id}
label={get(
EventSchema[education],
"label"
)}
variant="outlined"
/>
)}
/>
</FormControl>
</Grid>
<Grid item xs={5}>
<TextField
label="Percentage"
name={percentageId}
variant="outlined"
fullWidth
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
data-id={idx}
id={percentageId}
value={
formState.dynamicEducationBar[idx][
educationpercentage
] || ""
}
error={
checkErrorInDynamicBar(
educationpercentage,
val
)["error"]
}
helperText={
checkErrorInDynamicBar(
educationpercentage,
val
)["error"]
? checkErrorInDynamicBar(
educationpercentage,
val
)["value"]
: null
}
placeholder={get(
EventSchema[educationpercentage],
"placeholder"
)}
onChange={event => {
handleChangeForDynamicGrid(
educationpercentage,
event,
null,
val,
false,
true
);
}}
/>
</Grid>
<Grid item xs={2}>
{idx > 0 ? (
<DeleteForeverOutlinedIcon
onClick={e =>
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? null
: clickOnDelete(val, idx)
}
style={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? { color: "gray", fontSize: "24px" }
: { color: "red", fontSize: "24px" }
}
/>
) : (
""
)}
</Grid>
</Grid>
</CardContent>
</Card>
);
})}
<div className={classes.btnspaceadd}>
<Grid item xs={12} md={3} lg={3} xl={3}>
<YellowButton
type="button"
color="primary"
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: educations.length
? false
: true
}
variant="contained"
className={classes.add_more_btn}
onClick={e => {
addNewRow(e, education);
}}
>
{genericConstants.ADD_MORE_TEXT}
</YellowButton>
</Grid>
</div>
</Card>
</Grid>
</Grid>
</Grid>
</CardContent>
<Grid item xs={12} className={classes.CardActionGrid}>
<CardActions className={classes.btnspace}>
<Grid item xs={12}>
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={3}>
<Grid item md={2} xs={12}>
<YellowButton
type="submit"
color="primary"
variant="contained"
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
>
{genericConstants.SAVE_BUTTON_TEXT}
</YellowButton>
</Grid>
<Grid item md={2} xs={12}>
<GrayButton
type="button"
color="primary"
variant="contained"
to={routeConstants.MANAGE_EVENT}
>
{genericConstants.CANCEL_BUTTON_TEXT}
</GrayButton>
</Grid>
</Grid>
</Grid>
</Grid>
</CardActions>
</Grid>
</form>
</Card>
</Grid>
<Backdrop className={classes.backDrop} open={backdrop}>
<CircularProgress color="inherit" />
</Backdrop>
</Grid>
);
}