public class ToDoListController {
public List<TaskWrapper> tasks {get; set;}
public String newTaskSubject {get; set;}
public ToDoListController() {
tasks = new List<TaskWrapper>();
loadTasks();
}
private void loadTasks() {
tasks.clear();
for (Task t : [SELECT Id, Subject, Status, ActivityDate FROM Task WHERE WhoId = :UserInfo.getUserId() ORDER BY ActivityDate ASC NULLS FIRST]) { // Filter tasks for current user
tasks.add(new TaskWrapper(t));
}
}
public PageReference addTask() {
if (String.isBlank(newTaskSubject)) {
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Task subject cannot be empty.'));
return null;
}
Task newTask = new Task(Subject = newTaskSubject, WhoId = UserInfo.getUserId()); // Assign the task to the current user
try {
insert newTask;
newTaskSubject = ''; // Clear the input field
loadTasks(); // Refresh the task list
} catch (Exception ex) {
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error creating task: ' + ex.getMessage()));
}
return null;
}
public PageReference toggleTaskStatus() {
List<Task> tasksToUpdate = new List<Task>();
for (TaskWrapper tw : tasks) {
if (tw.isSelected) {
tw.task.Status = (tw.task.Status == 'Completed') ? 'Not Started' : 'Completed';
tasksToUpdate.add(tw.task);
}
}
try {
update tasksToUpdate;
loadTasks();
} catch (Exception ex) {
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error updating tasks: ' + ex.getMessage()));
}
return null;
}
public class TaskWrapper {
public Task task {get; set;}
public Boolean isSelected {get; set;}
public TaskWrapper(Task t) {
task = t;
isSelected = false;
}
}
}