Create new custom field using JSOM in Project Server or Project Online
Hello Readers !
Thanks for reading the article. In this article, we’ll see how to create Project level custom field of type Text using JavaScript Object Model (JSOM) upon clicking of a button. We usually deal with updating the custom fields using JSOM but creating a custom field using programmatically hardly comes for the requirement. But good to know how things are inter related and incase if there’s any scenario to create a custom field, this code will help to do it dynamically.
Link the below code to Content editor webpart in the PDPs.
< script src = "https://code.jquery.com/jquery-3.4.1.min.js" integrity = "sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin = "anonymous" > < /script> <script type = "text/javascript" src = "/_layouts/15/sp.runtime.js" > < /script> <script type = "text/javascript" src = "/_layouts/15/sp.js" > < /script> <script type = "text/javascript" src = "/_layouts/15/ps.js" > <input type = "button" id = "btnCreateCf" class = "createCf" value = "Click to Create" / > <script type = "text/javascript" > $(document).ready(function () { $("#btnCreateCf").click(function () { GetCustomFieldsInfo(); }); }); var cfObj, context, fieldType, projEntity, entityTypes; function GetCustomFieldsInfo() { context = PS.ProjectContext.get_current(); fieldType = PS.CustomFieldType.TEXT; entityTypes = context.get_entityTypes(); projEntity = entityTypes.get_projectEntity(); cfObj = context.get_customFields(); context.load(cfObj); context.load(entityTypes); context.load(projEntity); context.executeQueryAsync(Createfield, onFailed); } function Createfield() { //console.log(fieldType); //debugger; try { var newcf = new PS.CustomFieldCreationInformation(); var idvalue = NewGuid(); newcf.set_name("Xyz custom field"); newcf.set_description("This was created for testing"); newcf.set_entityType(projEntity); newcf.set_fieldType(fieldType); newcf.set_isMultilineText(false); newcf.set_isRequired(true); newcf.set_isWorkflowControlled(false); newcf.set_id(idvalue); cfObj.add(newcf); cfObj.update(); context.load(cfObj); context.executeQueryAsync(QuerySucceeded, onFailed); } catch (ex) { console.log("error : " + ex); } } function QuerySucceeded() { console.log("done"); } function onFailed(error) { alert('There is an error while fetching custom fields. ' + error); } // Function to generate GUIDs (https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript/2117523) function NewGuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }) } </script>
Thanks for reading the article. Happy coding 🙂
Recent Comments