function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dominic SharpeDominic Sharpe 

OnClick Javascript Button for Tasks

I'm a beginner when it comes to Javascript. We have an existing custom button that creates a new task on the Contact object. Here's the existing code:

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}

var myTask = new sforce.SObject("Task");
myTask.WhoId = "{!Contact.Id}";
myTask.Subject = "Follow Up";
sforce.connection.create([myTask]);
window.location.reload();

However, our requirements have changed. We now need the button to work ONLY when all tasks on the Contact are CLOSED. And instead of creating the task right away, the button should take the user to the task edit page to be able to enter comments. The user will save the task manually.

How do I use javascript to make sure that all tasks are closed?
How do I redirect the user to the task edit page?

Any tips and/or sample code I could work with would be of great help
@LaceySnr - Matt Lacey@LaceySnr - Matt Lacey

I think you've reached the point where you'd be better off using a custom button that routes to a Visualforce page. That page could check the status of existing tasks in it's init method quite easily, and then could either display an error message and list of tasks if some are open, or redirect to the edit page by returning a page reference with the standard URL.

 

The page controller would look roughly like this:

public class ContactTaskChecker
{
  private Contact c;
  public List<Task> openTasks;

  public ContactTaskChecker(ApexPages.StandardController sc)
  {
    c = (Contact)sc.GetRecord();
  }

  public PageReference Init()
  {
    // check for existing open tasks (limit to 10 so as not to overwhelm the user)
    openTasks = [select Id, Subject from Task where WhoId = : c.Id and Status != 'Completed' limit 10];

    if(openTasks.Size() > 0)
    {
      return null;
    }
    else
    {
      return new ApexPages.PageReference('00T/e?who_id=' + c.Id + '&retURL=' + c.Id);
    }
  }

}

Then you just need to implement a page that uses this extension controller:
 

<apex:page standardController="Contact" extensions="ContactTaskChecker" action="{!Init}">
  <!-- use an apex repeat or similar to display the open tasks -->
</apex:page>