+ Start a Discussion
MRutterMRutter 

What's wrong with this Apex code?

I and trying to use Apex to create a new Task, then return to the user with the new Task in Edit mode where the user can edit and save the new Task

 

This is what I have:

// Apex class for a new Tour on Lead.
// Called from VF Page LeadTourPg

public class NewLeadTour{
 public Lead si;
 public NewLeadTour() {}

// get ID of current Page (a Lead in this case)  
  public PageReference init() {
    Id siId = ApexPages.currentPage().getParameters().get('id');
 
       
//Declare Variables and strings 
    Lead lead;
    Account acc;   
    Task tsk;
   

    String CurrUser = UserInfo.getUserId();    //Get Current User
    
 //Get variables from current Lead Record   
    try {
      if (si==null)
      si = [SELECT Id, Name, OwnerID FROM lead WHERE Id = :siId];
    }
      catch(Exception e) {
    }
 
//Create a scheduled task
    if(si.Name!=null){   
    tsk = new Task();
    tsk.whoId = si.Id;
    tsk.OwnerId = currUser; 
    tsk.Subject = 'New Tour for ' + si.Name;
    tsk.Status = 'Not Started';
    //tsk.Description = 'User = '+ currUser;
    tsk.Priority = 'Normal';
    tsk.OwnerID = si.OwnerID;
    tsk.ActivityDate = date.today()+2;
  
try{
insert tsk;
}catch (Exception ex){system.debug('error creating a scheduled Task:'+ex);} 
}
 
return (new ApexPages.StandardController(tsk)).edit();
      
//return new PageReference('/'+tsk.Id);     
 
    
    }
    }

 

This does create a new Task and shows the new Task to me in edit mode.

However, when I edit the Task and click Save, the Task is saved, but I still see a Task in edit mode.  I cannot get out of this edit mode

 

Something wrong with this statment?

return (new ApexPages.StandardController(tsk)).edit();

 

Best Answer chosen by Admin (Salesforce Developers) 
Jia HuJia Hu
after you insert the task, try to return like,
new ApexPages.StandardController(tsk).view();

All Answers

Jia HuJia Hu
after you insert the task, try to return like,
new ApexPages.StandardController(tsk).view();
This was selected as the best answer
MRutterMRutter

Thanks for the suggestion.

 

This works, but then I have to click EDIT to edit the newly created task.

 

What I am looking for is a way to return with the new task in edit mode.