JXA for Creating new Project


#1

Can someone tell me what’s wrong with this “check for project or create” snippet on Omnifocus 3? It fails on the TODO line below (“target_project” is a string with a simple name):

var TaskApp = Application("Omnifocus")
TaskApp.includeStandardAdditions = true
var omnifocus_doc = TaskApp.defaultDocument
console.log(`Omnifocus Doc: ${omnifocus_doc.name()}`)
console.log("Setting target project: "+target_project)
var matching_projects = omnifocus_doc.flattenedProjects.whose({name: target_project})
var taskapp_project = null
if (matching_projects.length == 0) {
  console.log(`WARNING - Cannot find project ${target_project}. Creating it..`)
  taskapp_project = TaskApp.Project({
    name: target_project, status: 'active'
  })
  // TODO execution error: Error on line 44: Error: Can't get object. (-1728)
  omnifocus_doc.projects.add(taskapp_project)
} else {
  taskapp_project = matching_projects[0]
}
console.log(`Using project ${taskapp_project.name()}`)

#2

Hi David, this is I think you want omnifocus_doc.projects.push(taskapp_project) instead of omnifocus_doc.projects.add(taskapp_project):

var target_project = "My First Auto-created Project";

var TaskApp = Application("Omnifocus")
TaskApp.includeStandardAdditions = true
var omnifocus_doc = TaskApp.defaultDocument
console.log(`Omnifocus Doc: ${omnifocus_doc.name()}`)
console.log("Setting target project: "+target_project)
var matching_projects = omnifocus_doc.flattenedProjects.whose({name: target_project})
var taskapp_project = null
if (matching_projects.length == 0) {
  console.log(`WARNING - Cannot find project ${target_project}. Creating it..`)
  taskapp_project = TaskApp.Project({
    name: target_project, status: 'active'
  })
  
  // TODO execution error: Error on line 44: Error: Can't get object. (-1728)
  omnifocus_doc.projects.push(taskapp_project)
} else {
  taskapp_project = matching_projects[0]
}
console.log(`Using project ${taskapp_project.name()}`)

Also see https://gist.github.com/doug4j/5fc27ddb926b19a71f939f0c855988d3