CodeX Scripts for Tasks | Help | Zoho Projects

CodeX Scripts for Tasks

CodeX Scripts in Zoho Projects are advanced conditional logic scripts that help enforce specific rules and validations. Users can control how and when tasks can be created, edited, or transitioned. This ensures better compliance and process alignment. Refer here for CodeX Scripts for Projects.

Info
CodeX Scripts are currently available as a limited release. To enable this feature for your portal, please contact support@zohoprojects.com

Use Cases :

Create a Task

Creates a task using the selected layout and task list and update the task with necessary information.
Code:
  1. function main() {
  2.   try {
  3.     const layoutId = current.record.layoutId; // Choosen Layout Id
  4.     const moduleId = current.record.moduleId; // Choosen Module Id
  5.     const layout = client.getLayoutById(layoutId, moduleId);

  6.     const newTask = new Record(layout);

  7.     newTask.projectId = current.record.projectId;
  8.     newTask.name = "Roles and responsib";
  9.     newTask.tasklistId = "242942000000297017" // Tasklist ID

  10.     const user1 = variables.user1.value; // ZPUID of user1 is stored in variables
  11.     const user2 = variables.user2.value; // ZPUID of user2 is stored in variables

  12.     const addedTask = client.save(newTask);

  13.     addedTask.name = "Roles and responsibilities";
  14.     addedTask.status = "242942000000040005"; // status Id based on layout. Here, 242942000000040005 corresponds to 'In Progress' status
  15.     addedTask.description =
  16.       "This is a task to define roles and responsibilities.";
  17.     addedTask.start_date = "2025-12-09T12:00:00+05:30"; //start date should be proivded in ISO date and time formate
  18.     addedTask.end_date = "2025-12-12T12:00:00+05:30"; // end date should be proivded in ISO date and time formate
  19.     addedTask.owners_and_work = {
  20.       work_unit: "hours_per_day", // Possible values: %, hours, %_per_day, hours_per_day
  21.       total_work_value: "2160", // total work value based on work unit
  22.       work_type: "standard_work", // Possible values: standard_work, flexible_work
  23.       owners: [
  24.         {
  25.           owner: {
  26.             id: user1,
  27.           },
  28.           work_value: "540", // work value assigned to the owner based on work unit
  29.         },
  30.       ],
  31.     };
  32.     addedTask.teams = ["242942000000090845", "242942000000090855"]; // Team IDs

  33.     addedTask.completion_percentage = "50"; // Completion percentage value between 0 to 100
  34.     addedTask.billing_type = "1"; // Possible values: 0 (None), 1 (Billable), 2 (Non-Billable)
  35.     addedTask.single_line = "A single line custom field";
  36.     addedTask.pick_list = "Option 1"; // Picklist option name
  37.     addedTask.multi_line = "A multi line\ncustom field";
  38.     addedTask.multi_select = ["Option 1", "Option 2", "Option 3"]; // Multi select picklist option names
  39.     addedTask.user_pick_list_select_roles = "242942000000082031"; // Role ID
  40.     addedTask.user_pick_list_all_users = user1;
  41.     addedTask.user_pick_list_select_users = user2;
  42.     addedTask.multi_user_pick_list_all_users = [user1, user2];
  43.     addedTask.multi_user_pick_list_select_users = [user1, user2];
  44.     addedTask.date_field = "2025-12-09"; // Date should be provided in ISO date format
  45.     addedTask.date_time_field = "2025-12-09T12:00:00+05:30"; // Date time should be provided in ISO date and time format
  46.     addedTask.checkbox_field = "true";
  47.     addedTask.currency_field = "40000"; // Currency value
  48.     addedTask.percentage_field = "25"; // Percentage value between 0 to 100
  49.     addedTask.number_field = "450"; // Number value
  50.     addedTask.decimal_field = "1.234"; // Decimal value
  51.     addedTask.email_field = "zylker@zoho.com"; // Email address
  52.     addedTask.phone_field = "1234567890"; // Phone number
  53.     addedTask.url_field = "https://zylker.com/"; // URL
  54.     client.save(addedTask);
  55.   } catch (error) {
  56.     console.log(error);
  57.     throw new ScriptError(error); // Rethrow the error as a ScriptError which will be shown in Projects UI.
  58.   }
  59. }

Restrict Task Creation When Project Baseline is set: 

Restricts task creation if any baseline exists for the project to maintain the integrity of the project’s original plan.
Code:
  1. function main() {
  2.  
  3.     const url = `https://projects.zoho.com/api/v3/portal/${current.org.zohoOrgId}/projects/${current.record.projectId}/baselines`
  4.     const request = new HttpRequest();
  5.     request.url(url);
  6.     request.method('get');
  7.     request.connection('zprojects')
  8.  
  9.     const response = request.execute();
  10.     const baselines = response.asJson()?.statusMessage?.responseText?.BASELINEDETAILS;
  11.  
  12.     if(baselines && baselines instanceof Array && baselines.length > 0) {
  13.         throw new ScriptError('Cannot create new tasks after baseline is set');
  14.     }
  15. }

Restrict Subtask Creation Beyond One Level 

Restricts creating a subtask under another subtask to maintain a simple and manageable task hierarchy, allowing only one level of subtasks.
Code:
  1. function main() {
  2.     if(current.record.parent_task !== current.record.root_task) {
  3.         throw new ScriptError('Disable subtasks creation with more than 1 level');
  4.     }
  5. }
  6.  
  7.  Restrict Task Completion with Open Issues 
  8. Restricts closing a task if any associated issue is not in Closed or Canceled status to ensure all related issues are resolved.
  9.  
  10. function main() {
  11.  
  12.     console.log('started');
  13.     console.log(`${current.affectedFields}`);
  14.  
  15.     if (!current.affectedFields.status) {
  16.         return;
  17.     }
  18.  
  19.     const statusDtl = client.getStatusDetails(current.module.id, current.record.layoutId, current.affectedFields.status.newValue);
  20.  
  21.     if (!statusDtl.isClosedStatus) {
  22.         return;
  23.     }
  24.     
  25.     const task = current.record;
  26.     const url = `https://projects.zoho.com/api/v3/portal/${current.org.zohoOrgId}/projects/${task.projectId}/tasks/${current.record.id}/associated-bugs`;
  27.  
  28.     const request = new HttpRequest();
  29.     request.url(url);
  30.     request.connection('zprojects');
  31.     const response = request.execute();
  32.     const associatedBugs = response.asJson()?.statusMessage?.responseText?.associated_bugs;
  33.  
  34.     if(!associatedBugs) {
  35.         return;
  36.     }
  37.  
  38.     for(let bug of associatedBugs) {
  39.         if(bug.issue.status_name !== 'Closed' || bug.issue.status_name !== 'Cancelled') {
  40.             throw new ScriptError('Open issues exist for this task');
  41.         }
  42.     }
  43.  
  44.     console.log(response.asJson()?.statusMessage?.responseText);
  45. }

Disable Task Creation in Projects with On-Hold status 

Restricts task creation if the associated project is marked as On Hold.
Code:
  1. function main() {
  2.  
  3.     const projectId = current.record.projectId;
  4.     const moduleItr = client.getModules();
  5.  
  6.     /**
  7.      * @type {Module}
  8.      */
  9.     let module
  10.  
  11.     console.log('started');
  12.     for (let mod of moduleItr) {
  13.         console.log(`${mod}`);
  14.         if (mod.name === 'Projects') {
  15.             module = mod;
  16.         }
  17.     }
  18.  
  19.     if (!module) {
  20.         return;
  21.     }
  22.  
  23.     let projectDtl = client.getRecordById(module.id, projectId);
  24.     let statusDtl = client.getStatusDetails(module.id, projectDtl.layoutId, projectDtl.status);
  25.  
  26.     if (statusDtl.name === 'zp.projstatus.onhold') {
  27.         throw new ScriptError('Task Creation disabled for On Hold Projects');
  28.     }
  29. }
  30.  

 Restrict Manual Date Change After Status Update 

Restricts editing start date, end date, or duration if the status is not the layout’s default.
Code:
  1. function main() {
  2.  
  3.     //base condition #1
  4.     if (!current.affectedFields.start_date
  5.         && !current.affectedFields.end_date
  6.         && !current.affectedFields.duration_value
  7.         && !current.affectedFields.duration_unit) {
  8.         return;
  9.     }
  10.  
  11.     const statusDtl = client.getStatusDetails(current.module.id, current.record.layoutId, current.record.status);
  12.     console.log(`${statusDtl}`);
  13.     
  14.     if (!statusDtl.isLayoutDefault) {
  15.         throw new ScriptError('Start Date and End date change are only allowed in default status');
  16.     }
  17. }
  18.  

Restrict Task Closure if Open Subtasks Exist  

Restricts the parent task's status to change to Closed if any open subtasks exists. This ensures that the parent task cannot be marked as complete until all its subtasks are closed.
Code:
  1.  
  2. function main() {
  3.  
  4.     console.log(current.affectedFields.toString());
  5.  
  6.     //base condition handling
  7.     if (!current.affectedFields?.status) {
  8.         return;
  9.     }
  10.  
  11.     const url = `https://projects.zoho.com/restapi/portal/${current.org.zohoOrgId}/projects/${current.record.projectId}/tasks/${current.record.id}/subtasks/`;
  12.     let hasMore = true;
  13.     const range = 200;
  14.     let index = 1;
  15.     console.log(url);
  16.  
  17.     while (hasMore) {
  18.         let request = new HttpRequest();
  19.         request.url(url);
  20.         request.connection('zprojects');
  21.         request.params({ index, range });
  22.  
  23.         const response = request.execute();
  24.  
  25.         console.log(response.asText());
  26.         /**
  27.          * @type {[]}
  28.          */
  29.         const tasks = response.asJson()?.statusMessage?.responseText?.tasks;
  30.  
  31.         //no subtasks present for current task
  32.         if (!tasks || tasks.length == 0) {
  33.             console.log('No subtasks exists for current task');
  34.             return;
  35.         }
  36.  
  37.         hasMore = tasks.length == range;
  38.         index += range;
  39.  
  40.         console.log(tasks);
  41.         console.log(tasks.length);
  42.  
  43.         for (let task of tasks) {
  44.             console.log(task.completed);
  45.             if (!task.completed) {
  46.                 throw new ScriptError('Open subtasks remain for this task.');
  47.             }
  48.         }
  49.     }
  50.  
  51.  
  52. }

Restrict Status Change if Predecessors are Open 

Restricts status updates if any of the predecessor tasks are incomplete to ensure dependency logic so that a successor task can only proceed once its predecessors are closed.
Code:
  1. function main() {

  2.     console.log(current.affectedFields.toString());
  3.     
  4.     //base condition handling
  5.     if(!current.affectedFields?.status) {
  6.         return; 
  7.     }

  8.     const url = `https://projects.zoho.com/restapi/portal/${current.org.zohoOrgId}/projects/${current.record.projectId}/tasks/${current.record.id}/`;
  9.     console.log(url);
  10.     
  11.     let request = new HttpRequest();
  12.     request.url(url);
  13.     request.connection('zprojects');

  14.     const response = request.execute();
  15.     const taskDependencyDtl = response.asJson()?.statusMessage?.responseText?.tasks[0]?.dependency;

  16.     //no dependency present in previous task
  17.     if(!taskDependencyDtl || !taskDependencyDtl?.predecessor) {
  18.         return;
  19.     }

  20.     console.log(taskDependencyDtl);

  21.     for(let predecessorId of taskDependencyDtl.predecessor) {
  22.         console.log(predecessorId);
  23.         if(!taskDependencyDtl.dependencyDetails[predecessorId]?.IS_COMPLETED) {
  24.             throw new ScriptError('Open predecessor tasks exists, please close them to proceed');
  25.         }
  26.     }

  27. }

  28. task_owner_status_update_restrict
  29. function main() {

  30.     const task = current.record;
  31.     const affectedFields = current.affectedFields;

  32.     if(affectedFields.status) {
  33.         if(!task._owners || !task._owners.includes(current.user.id)) {
  34.             throw new ScriptError('Only task owner can edit the status');
  35.         }
  36.     }

  37. }

 Restrict Subtask Creation 

Restricts subtask creation to maintain a flat task structure.
Code:
  1. function main() {
  2.     
  3.     let task = current.record;
  4.  
  5.     /**
  6.      *
  7.      * @type Number
  8.      */
  9.     let startDate = task.start_date;
  10.     Logger.info('Parent ID: ' + task.parent_task);
  11.     Logger.info('Root Task ID: ' + task.root_task);
  12.  
  13.     // console.log(JSON.stringify(variables.blockSubTasks));
  14.     if(task.parent_task || task.root_task) {
  15.         Logger.info("Subtask creation is disabled");
  16.         throw new ScriptError(JSON.stringify(variables.blockSubTasks.value));     
  17.     }
  18.  
  19.     //Similar case >>> Subtasks shouldn't be created under the closed parent task.
  20. }
  21.  

Update Task Duration and Status Based on Conditions 

Update task duration and status based on a specific custom field and current status.
For example, this script updates the duration of a task and its status when specific conditions are met:
  1. If the current status of the task is “On Hold”, it automatically changes the status to a specific ID (e.g., "In Progress").
  2. If a specific value is selected in a multi-select custom field, it sets the duration to 30 days.
  3. It also checks and logs the task’s billing type and affected fields.
Code:
  1. function main() {
  2.  
  3.     /**
  4.      * @type {CurrentTask}
  5.      */
  6.     // const task = client.getRecordById('5000000000134', '5000000291025');
  7.     // console.log(task.name);
  8.     // throw new Error(task);
  9.     //5000000179016 = corn
  10.     let task = current.record;
  11.     console.log(`id: ${task.id}`);
  12.     console.log(current.affectedFields);
  13.     console.log(`Task Billing type ${task.billing_type}`);
  14.     console.log(`Task Biling Type BILLABLE ${TaskBillingType.BILLABLE}`);
  15.     console.log(`Task Biling Type NON_BILLABLE ${TaskBillingType.NON_BILLABLE}`);
  16.     console.log(`Task Biling Type NONE ${TaskBillingType.NONE}`);
  17.  
  18.     const statusDetails = client.getStatusDetails(task.moduleId, task.layoutId, task.status);
  19.     if(statusDetails.name === 'On Hold') {
  20.         task.status = '5000000000362';
  21.         client.save(task);
  22.     }
  23.     console.log(JSON.stringify(statusDetails));
  24.     if(task.weightage.includes("Medium") { //check if the multi select field is some options
  25.         console.log('setting status to In Progress');
  26.         task.duration_unit = TaskDurationUnit.DAYS;
  27.         task.duration_value = 30;
  28.     }
  29.  
  30.  
  31. }

 Restrict Edits for Archived Projects 

Restricts any update to a task if its project is archived to ensure that no task edits can be made under such projects.
Code:
  1. function main() {
  2.     let task = current.record;
  3.  
  4.     let projectId = task.projectId;
  5.     const moduleItr = client.getModules(0, 10);
  6.     //projects module id: 5000000000380
  7.     let moduleId;
  8.     console.log(JSON.stringify(current.affectedFields));
  9.     while(moduleItr.hasNext()) {
  10.         let moduleObj = moduleItr.next();
  11.         if(moduleObj.name == 'Projects') {
  12.             moduleId = moduleObj.id;
  13.         }
  14.         
  15.     }
  16.     let project = client.getRecordById(moduleId, projectId);
  17.  
  18.     if(project._status == 'archived') {
  19.         throw new ScriptError("Edits are disabled for archived projects");
  20.     }
  21.  
  22.  
  23. }
  24.  

Restricts Past Start Dates

Throws an error if the selected start date is in the past to maintain accurate schedules.
Code:
  1. function main() {
  2. let task = current.record;
  3. let date = Date.now();
  4. for(let key of Object.keys(current)) {
  5. console.log(key);
  6. }
  7.  
  8. console.log('Checking current');
  9. console.log('Checking current.user');
  10. console.log(`current.user.zuid: ${current.user.zuid}`);
  11. console.log(`current.user.email ${current.user.email}`);
  12. console.log(`current.user.id ${current.user.id}`);
  13. console.log('checking current.module');
  14. console.log(`current.module.name ${current.module.name}`);
  15. console.log(`current.module.id ${current.module.id}`);

  16. console.log('checking org');
  17.     console.log(`current.org.name ${current.org.zohoOrgId}`);
  18. console.log(`current.org.id ${current.org.orgId}`);
  19. console.log(`current.org.portalName ${current.org.portalName}`);
  20. console.log(`current.org.id ${current.org.name}`);
  21.  
  22.   /**********LOGIC IS BELOW HERE*************/
  23.  
  24. const startDate = new Date(task.start_date)
  25. if(date > startDate) {
  26. console.log('Start date is in past date');
  27. throw new ScriptError('Start date cannot be in the past');
  28. }
  29. }

Restrict Editing Task on a Condition

Restricts any updates to the task if the checkbox field is enabled, except when changing the checkbox itself to prevent unintended changes.
Code:
  1. function main() {
  2.  
  3.     const affectedFields = current.affectedFields;
  4.     const task = current.record;
  5.  
  6.     if(affectedFields && typeof affectedFields['checkbox_cf'] != 'undefined') {
  7.         return;  //Do nothing in case the checkbox itself is updated.
  8.     }
  9.  
  10.     //boolean value for checkbox type field
  11.     if(task.checkbox_cf) {
  12.         throw new ScriptError('The check box is enabled, task is locked. ')
  13.     }
  14. }
  15.  
Got an idea for how you would like CodeX to work in your project setup? Drop your use case in the comments below!

More Reads

      Create. Review. Publish.

      Write, edit, collaborate on, and publish documents to different content management platforms.

      Get Started Now


        Access your files securely from anywhere

          Zoho CRM Training Programs

          Learn how to use the best tools for sales force automation and better customer engagement from Zoho's implementation specialists.

          Zoho CRM Training
            Redefine the way you work
            with Zoho Workplace

              Zoho DataPrep Personalized Demo

              If you'd like a personalized walk-through of our data preparation tool, please request a demo and we'll be happy to show you how to get the best out of Zoho DataPrep.

              Zoho CRM Training

                Create, share, and deliver

                beautiful slides from anywhere.

                Get Started Now


                  Zoho Sign now offers specialized one-on-one training for both administrators and developers.

                  BOOK A SESSION







                              Quick LinksWorkflow AutomationData Collection
                              Web FormsEnterpriseOnline Data Collection Tool
                              Embeddable FormsBankingBegin Data Collection
                              Interactive FormsWorkplaceData Collection App
                              CRM FormsCustomer ServiceAccessible Forms
                              Digital FormsMarketingForms for Small Business
                              HTML FormsEducationForms for Enterprise
                              Contact FormsE-commerceForms for any business
                              Lead Generation FormsHealthcareForms for Startups
                              Wordpress FormsCustomer onboardingForms for Small Business
                              No Code FormsConstructionRSVP tool for holidays
                              Free FormsTravelFeatures for Order Forms
                              Prefill FormsNon-Profit

                              Intake FormsLegal
                              Mobile App
                              Form DesignerHR
                              Mobile Forms
                              Card FormsFoodOffline Forms
                              Assign FormsPhotographyMobile Forms Features
                              Translate FormsReal EstateKiosk in Mobile Forms
                              Electronic Forms
                              Drag & drop form builder

                              Notification Emails for FormsAlternativesSecurity & Compliance
                              Holiday FormsGoogle Forms alternative GDPR
                              Form to PDFJotform alternativeHIPAA Forms
                              Email FormsFormstack alternativeEncrypted Forms

                              Wufoo alternativeSecure Forms

                              TypeformWCAG


                                          Create. Review. Publish.

                                          Write, edit, collaborate on, and publish documents to different content management platforms.

                                          Get Started Now




                                                            You are currently viewing the help pages of Qntrl’s earlier version. Click here to view our latest version—Qntrl 3.0's help articles.




                                                                Manage your brands on social media


                                                                  • Desk Community Learning Series


                                                                  • Digest


                                                                  • Functions


                                                                  • Meetups


                                                                  • Kbase


                                                                  • Resources


                                                                  • Glossary


                                                                  • Desk Marketplace


                                                                  • MVP Corner


                                                                  • Word of the Day


                                                                  • Ask the Experts


                                                                    Zoho Sheet Resources

                                                                     

                                                                        Zoho Forms Resources


                                                                          Secure your business
                                                                          communication with Zoho Mail


                                                                          Mail on the move with
                                                                          Zoho Mail mobile application

                                                                            Stay on top of your schedule
                                                                            at all times


                                                                            Carry your calendar with you
                                                                            Anytime, anywhere




                                                                                  Zoho Sign Resources

                                                                                    Sign, Paperless!

                                                                                    Sign and send business documents on the go!

                                                                                    Get Started Now




                                                                                            Zoho TeamInbox Resources





                                                                                                      Zoho DataPrep Demo

                                                                                                      Get a personalized demo or POC

                                                                                                      REGISTER NOW


                                                                                                        Design. Discuss. Deliver.

                                                                                                        Create visually engaging stories with Zoho Show.

                                                                                                        Get Started Now








                                                                                                                            • Related Articles

                                                                                                                            • Working with CodeX Scripts

                                                                                                                              CodeX Scripts allows users to define custom logic that runs automatically based on events in the modules such as when a project or task is created, updated, or deleted. These scripts help enforce validations, restrict actions, or apply conditions ...
                                                                                                                            • CodeX Scripts - Intro

                                                                                                                              CodeX Scripts let you define custom logic that runs automatically when users interact with tasks or projects. It allows users to control how the module behaves based on certain conditions. Users can write scripts using JavaScript SDKs to trigger ...
                                                                                                                            • JavaScript SDK for CodeX Scripts

                                                                                                                              Codex Scripts in Zoho Projects allow users to customize how the projects and tasks operate. Using these scripts, users can automate validations and actions, integrate external systems, and retrieve or update the data. CodeX Scripts are currently ...
                                                                                                                            • CodeX Scripts for Projects

                                                                                                                              CodeX Scripts in Zoho Projects are advanced conditional logic scripts that help enforce specific rules and validations. Users can control how and when a project can be created, edited, or transitioned. This ensures better compliance and process ...
                                                                                                                            • CodeX Credits

                                                                                                                              CodeX credits allows admins to monitor and analyze the number of CodeX script executions in Zoho Projects. Each time a script is executed, it uses one credit. Credits are allocated based on the organizations' subscription plan and will reset every ...
                                                                                                                              Wherever you are is as good as
                                                                                                                              your workplace

                                                                                                                                Resources

                                                                                                                                Videos

                                                                                                                                Watch comprehensive videos on features and other important topics that will help you master Zoho CRM.



                                                                                                                                eBooks

                                                                                                                                Download free eBooks and access a range of topics to get deeper insight on successfully using Zoho CRM.



                                                                                                                                Webinars

                                                                                                                                Sign up for our webinars and learn the Zoho CRM basics, from customization to sales force automation and more.



                                                                                                                                CRM Tips

                                                                                                                                Make the most of Zoho CRM with these useful tips.



                                                                                                                                  Zoho Show Resources