• Vader
  • NEWBIE
  • 55 Points
  • Member since 2013

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 13
    Questions
  • 18
    Replies

I have a visualforce page that I wamt to hook to a custom button on the Contact page layout.  When a user clicks on the button it will open the visualforce and display a list of records from a custom object that is related to a specific contact.

 

I setup the page using the standardController="Contact" and the extensions attribute...i.e. extensions="MyControllerExtension"

 

MyControllerExtension uses the StandardSetController so I can use pagination to page over the results, but I'm getting the error: Unknown constructor 'MyControllerExtension.MyControllerExtension(ApexPages.StandardController controller).

 

If I use the custom controller...i.e. controller="MyControllerExtension" then the visualforce page is not accessible to select as an option for the custom button.  How can I use the standardSetController in the my controller and still use the standardController from my VF page so I can hook the custom button to my page?

 

Thanks.

I have a visualforce page for both Task View and Task Edit.  I have added the Attachments related list to the standard page layout and added :

<apex:relatedList list="Attachments" subject="{!$CurrentPage.parameters.id}" />

to the Task View page as a related list.



I can render the related list in the Task Edit page with the same code but I am not able to get the "Attach File" button to show up.  I understand that this should only be visible when the task is being edited.  I have tried updating the visualforce apiversion from 25 to 29 with no luck there either.

Anytime I use "AttachedContentDocuments" or "CombinedAttachments" in place of "Attachments" in the code, I get an error message saying it's not a valid child of the Task object.

Any help would be appreciated.  This should be simple... I guess I am just not seeing it.


  • May 15, 2014
  • Like
  • 0

Synopsis:

There is a checkbox on the account named 'Private Account'.  If a user creates an opportunity and the account they reference has Private Account set to TRUE, I want to force a boolean field on the Opportunity name 'Private Opportunity' to also be set to TRUE at the time the opportunity is created or edited.  If the account does not have 'Private Account' set to TRUE, the user should be able to set the 'Private Opportunity' field to TRUE or FALSE without any intervention on the part of the trigger.

 

I have tried 4-5 different ways to do this and haven't been able to get it to work correctly.  Currently code below:

 

trigger validateOppAccountSharing on Opportunity (before insert, before update) {
	
	List<Opportunity> objOpps = [Select Account.Private_Account__c From Opportunity Where Id in: Trigger.new];
	
	for (Integer i = 0; i < Trigger.new.size(); i++) {
		if (objOpps[i].Account.Private_Account__c == true) {
			trigger.new[i].Private_Opportunity__c == TRUE;
		}
	}
}

 Right now I am getting an error that the 'Expression cannot be a statement.'  In other words my syntax or method of assigning TRUE to 'Private_Opportunity__c' is incorrect.

 

Any help is appreciated.

  • September 25, 2013
  • Like
  • 0

I have a VF page that uses the standard salesforce Task object  and is almost identical to the standard create task page from SFDC.  

 

When creating a task from an account, it populates the name of the account in the Related To field without any issues.  Same for Product, Contact, Case, etc.

 

The wierd issue is that when creating a Task from an Opportunity, I get the following error:  

Validation Errors While Saving Record(s)

There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Contact/Lead ID: id value of incorrect type: (record id here) "

 

I am not referencing any whoid or whatid fields, I am using the standard Task Controller with the standard task Save method and have no validation rules on the Activity or Opportunity objects that would even come close to generating this messag? 

 

Anyone know why I am getting this ONLY when trying to create a task from an opportunity record?

 

VisualForce

<apex:page standardController="Task" extensions="taskCreate">
		   
	<apex:sectionHeader title="{!$ObjectType.Task.label} Edit" subtitle="New {!$ObjectType.Task.name}"/>
	
	<apex:form >
	
		<apex:pageBlock title="{!$ObjectType.Task.label} Edit" mode="edit">
	        <apex:pageBlockButtons >
	                <apex:commandButton action="{!save}" value="Save"/>
	                <apex:commandButton action="{!saveAndAddInformed}" value="Save and Add Informed Users"/>
	                <apex:commandButton action="{!cancel}" value="Cancel"/>
	        </apex:pageBlockButtons>
	        <apex:pageBlockSection showHeader="true" title="Task Information" columns="2">
	                <apex:inputField required="true" value="{!Task.OwnerId}"/>
	                <apex:inputField value="{!Task.WhatId}"/>
	                <apex:inputField required="true" value="{!Task.Subject}"/>
	                <apex:inputField value="{!Task.WhoId}"/>
	                <apex:inputField value="{!Task.ActivityDate}"/>
	                <apex:pageBlockSectionItem />
	        </apex:pageBlockSection>
	        <apex:pageBlockSection showHeader="false" columns="1">
	                <apex:inputField style="width: 400px; height: 150px" value="{!Task.Description}" />
	        </apex:pageBlockSection>
	        <apex:pageBlockSection showHeader="true" title="Additional Information" columns="2">
	                <apex:inputField required="true" value="{!Task.Status}"/>
	                <apex:inputField required="true" value="{!Task.Priority}"/>
	        </apex:pageBlockSection>
	        
	        <apex:pageBlockSection showHeader="true" title="Notifications" columns="2">
	        	<apex:pageBlockSectionItem >
	        		<apex:inputCheckbox value="{!Task.Assignee_Notification__c}" id="assigneeNotification"/>
	        		<apex:outputLabel value="Send Notification Email (To Assignee)" />
	        	</apex:pageBlockSectionItem>
	        	
	        	<apex:pageBlockSectionItem >		        	
	        	</apex:pageBlockSectionItem>
	        	
	        	<apex:pageBlockSectionItem >
	        		<apex:inputCheckbox value="{!Task.Delegator_Notification__c}" id="delegatorNotification"/>
	        		<apex:outputLabel value="Receive Update Notifications" />
	        	</apex:pageBlockSectionItem>
	        	
	        </apex:pageBlockSection> 
		</apex:pageBlock>
		
		
	</apex:form>
</apex:page>

 

 

Apex for custom controller:

 

public class taskCreate {
	public Id tskId {get;set;}	
	private ApexPages.StandardController controller;	
	
	//*************************************************************
	//Constructor
	//*************************************************************
	public taskCreate(ApexPages.StandardController stdController) {
      // Save the standard controller so that we can use its methods later
      controller = stdController;
   }	
	
	//*************************************************************
	//Save the task and redirect to the informed users entry page
	//*************************************************************
	public PageReference saveAndAddInformed() {		
		PageReference taskPage;
			try {
				taskPage = controller.save();
				tskId = controller.getRecord().Id;
			} 
				catch (Exception ex) {
				// If there are caught exceptions, add them to the current page
				ApexPages.addMessages(ex);
			}
		
		//*************************************************************
		// If our task was successfully saved, there will be a non-null 
		// PageReference
		//*************************************************************		
		
		If (taskPage != null) {
			String longTaskId = String.valueOf(tskId);
			String shortTaskId = longTaskId.left(15);
			
			//PageReference tskInformed = new pagereference('/apex/informedUsers?tId='+tskId);
			PageReference tskInformed = new pagereference('/apex/informedUsers?tId='+shortTaskId);
			tskInformed.setRedirect(true);
  			return tskInformed;
  			
		}				
		else 			
		{
			return taskPage;
		} 

	}
	
	public static Task testTsk;

    static testMethod void taskCreateUnitTest() {    	
    	Test.startTest();
        testTsk = new Task(Subject='testTask'); 
        insert testTsk;        
        //Id tskId = task.Id;       

        PageReference pg = Page.informedUsers;
        Test.setCurrentPage(pg);          
              
        ApexPages.StandardController con = new ApexPages.StandardController(testTsk);
        taskCreate tCreate = new taskCreate(con); 
        
        tCreate.SaveAndAddInformed();
        Test.stopTest();        
    }
	
}

 

  • September 13, 2013
  • Like
  • 0

So I've come to realize that there are two errors that I am learning to dislike very much...

1)  Easilly the one I dislike the most is:  "System.NullPointerException: Attempt to de-reference a null object"

2) The second has become:  Save error: Constructor not defined: [ApexPages.StandardController].<Constructor>(xxxxx)

 

I've just written a half dozen or more Test Classes using the same syntax for creating the constructor in my test method but for some reason, this one is giving me a fit.

 

This class is an extension class.  Is there something I need to do different? The constructors in all my classes are set up almost identically so I would assume creating them in my test class would be as well.

 

public with sharing class taskMyDelegatedView {
	
	public Id tskId {get;set;}	
	public Id uID {get;set;}
	public String iView {get;set;}
	
	
	private ApexPages.StandardController controller;
	public taskMyDelegatedView(ApexPages.StandardController stdController) {
      controller = stdController;
   }
	
	Id currentUserId = userinfo.getUserId();	
	   
	public List<Task> getMyDelegatedTasks() {
        return [SELECT id, Subject, Description, Status, WhatId, What.Name, Owner.Name, OwnerId, CreatedBy.Name, CreatedById, ActivityDate, Task_Due_Date__c, LastModifiedDate FROM Task WHERE CreatedById =: currentUserId ORDER BY LastModifiedDate];        
    }
    
   
   String result='Click on a task subject to preview the latest notes.';
   public String getFetchedData() {
   		return result;
   } 
   
   public PageReference invokeService() {
   		Id id = System.currentPageReference().getParameters().get('id');
   		result = [SELECT Description FROM Task WHERE Id=:id].Description;
   		return null;   	
   }
   

    public static Task testTsk;
    public static taskMyDelegatedView testTaskMDV;
    public static Task_Informed_Users__c testInformedUser;
    public static User testUserId;
        
    static testMethod void informedUserListTest() {    	
    	Test.startTest();    		
    		
	    	testUserId = [SELECT ID FROM User WHERE LastName=: 'User2'];
	    	System.Debug(testUserId);
	    	
	        testTsk = new Task(Subject='testTask', description='ABC', ownerId=testUserId.Id); 
	        insert testTsk;
	        System.Debug(testTsk.Id);	        
	       	        
	            
	        testInformedUser = new Task_Informed_Users__c(Informed_user__c=testUserId.Id, Task_ID__c=testTsk.Id, Chatter_Notification__c=FALSE, Send_Email__c=FALSE);
	        insert testInformedUser;
	        System.Debug(testInformedUser.Id);

	        
	        Test.setCurrentPage(Page.delegatedTaskView);
		ApexPages.currentPage().getParameters().put('Id',testTsk.Id);
			
		ApexPages.Standardcontroller con = new ApexPages.Standardcontroller(testTaskMDV); //ERROR HAPPENING HERE
		taskMyDelegatedView tTMDV = new taskMyDelegatedView(con);
	        
	        system.runas(testUserId) {
				

		}
        
        Test.stopTest();        
    }


}

 

  • September 10, 2013
  • Like
  • 0

I am trying to get better coverage of a particular controller extension and am having a few issues with one particular line.  I have a custom object where I store a task Id and a user Id and a few other fields.  This class is meant to query, insert, or delete records in that object.

 

In the getInformedUsers method below, all the lines test fine with the exception of the Return property.  I keep getting a Attempt to dereference a null object error.  The only other place where I can't seem to get coverage is in the removeInformed method for the redirect lines.  

 

I am currently at 61% pass if I do not test the getInformedUsers method but would love figure out how to cover that as well.  Code below:

 

public with sharing class informedUserList {
	
	private ApexPages.StandardController controller;
	
	
	public informedUserList(ApexPages.StandardController stdController) {     
      controller = stdController;
   }	   
	public List<Task_Informed_Users__c> getInformedUsers() {
		
		String tskID = ApexPages.currentPage().getParameters().get('Id');
		String longTaskId = String.valueOf(tskId);
		String shortTaskId = longTaskId.left(15);	
		     
        return [SELECT id, Informed_User__r.Name, Chatter_Notification__c, Send_Email__c FROM Task_Informed_Users__c WHERE Task_Id__c =: shortTaskId];
    }   
    
	public PageReference addInformed() {		
		string tskId = ApexPages.currentPage().getParameters().get('Id');		
		
		PageReference tskInformed = new pagereference('/apex/informedUsers?tId='+tskId);
		tskInformed.setRedirect(true);
  		return tskInformed;  			

	}

	public PageReference removeInformed() {		
		string tskId = ApexPages.currentPage().getParameters().get('Id');
		Id iuRecId = System.currentPageReference().getParameters().get('iuRec');
		
		delete [select id from Task_Informed_Users__c where ID=: iuRecId ]; 

   		return null;
		
		PageReference tskInformed = new pagereference('/apex/taskDetail?Id='+tskId);
		tskInformed.setRedirect(true);
  		return tskInformed;  			

	}
	
    
    public static Task testTsk;
    public static Task_Informed_Users__c testInformedUser;
    public static ID testTaskId;
    public static User testUserId;
        
    static testMethod void informedUserListTest() {    	
    	Test.startTest();
    	
    	testUserId = [SELECT ID FROM User WHERE LastName=: 'User2'];
        testTsk = new Task(Subject='testTask', ownerId=testUserId.Id); 
        insert testTsk;
        testTaskId = testTsk.Id;
            
        testInformedUser = new Task_Informed_Users__c(Informed_user__c=testUserId.Id, Task_ID__c=testTaskId, Chatter_Notification__c=FALSE, Send_Email__c=FALSE);
        insert testInformedUser;
        
        Test.setCurrentPage(Page.taskDetail);
		ApexPages.currentPage().getParameters().put('tId',testTaskId);         
              
        ApexPages.StandardController con = new ApexPages.StandardController(testInformedUser);
        informedUserList tInformedUserList = new informedUserList(con); 
        
        tInformedUserList.addInformed();  //Tests Fine
      
        tInformedUserList.removeInformed(); //Tests all but the redirect code    
        
        tInformedUserList.getInformedUsers();  //Get Attempt to DeReference a Null Object error
           
        
        Test.stopTest();        
    }
      
}

 

  • September 09, 2013
  • Like
  • 0

 I have been given a business requirement to have a Chatter Feed notification added to records whenever a document is added (attached) to the Related Content Related List.  

 

I am not finding much information related to available objects or really which object I would have access to for Related Content to begin to look at any potential triggers.

 

Is this possible?  Any samples would be appreciated.

  • August 23, 2013
  • Like
  • 0

I am having trouble determining how to do this properly.    I have an Apex Class that has a list that is built based on a SOQL query into a custom object that contains Task IDs.  I want to use that list to iterate through the Task object to return the values below to another list object that is then referenced in a Visualforce data table by calling "{!getMyInformedTasks}". 

 

What is below just seems off in how it's constructed.  I am getting the error, "Save error: Variable does not exist: getMyInformedTasks"

 

 

        Id currentUserId = userinfo.getUserId();
	
	List<Task_Informed_Users__c> informedTaskList = [SELECT task_id__c FROM Task_Informed_Users__c WHERE informed_User__c =: currentUserId];
	
	public List<Task> getMyInformedTasks() {
		for(Task_Informed_Users__c tIU : informedTaskList) {
			for(Task t : tIU) {				
				getMyInformedTasks.add(t.Id);
				getMyInformedTasks.add(t.Subject);
				getMyInformedTasks.add(t.Description);
				getMyInformedTasks.add(t.Status);
				getMyInformedTasks.add(t.WhatId);
				getMyInformedTasks.add(t.What.Name);
				getMyInformedTasks.add(t.Owner.Name);
				getMyInformedTasks.add(t.OwnerId);
				getMyInformedTasks.add(t.CreatedBy.Name);
				getMyInformedTasks.add(t.CreatedById);
				getMyInformedTasks.add(t.ActivityDate);
				getMyInformedTasks.add(t.Task_Due_Date__C);							
			}
		}		
		return getMyInformedTasks;		
	}

 

  • August 19, 2013
  • Like
  • 0

I have a picklist that I am trying to generate from a class.  The idea is that when a user picks an item from the list that they will be redirected to the corresponding page.  When I use the code snippet below in a test page where the class is set as the "Controller=class" it works great.  However, when I add the class to another page as "extensions=class", the drop down list will not render any values.

 

Any ideas on how to get this to render properly.

 

Visualforce:

 

<apex:page standardController="Task" extensions="taskManagementRedirectPicklist" tabStyle="Task">
<apex:form >	
	<apex:pageBlock title="Selection Criteria">		
		
		<apex:pageBlockSection showHeader="false" title="Options" columns="3">
			<apex:pageBlockSectionItem >
				
				<apex:selectList value="{!picklistvalue}" size="1" >
			    	<Apex:selectOptions value="{!item}"/>
			    	<apex:actionSupport event="onchange" action="{!redirect}" />    
			    </apex:selectList>
			    		
			</apex:pageBlockSectionItem>
	    </apex:pageBlockSection>
	</apex:pageBlock>
</apex:form>
</apex:page>

 

Apex Class:

 

public with sharing class taskManagementRedirectPicklist {
	
	private ApexPages.StandardController controller;
	
	public taskManagementRedirectPicklist(ApexPages.StandardController stdController) {
      controller = stdController;
   }   
	
	public list<selectoption>item{get;set;}
	public string picklistvalue{get;set;}
	
	public taskManagementRedirectPicklist()
	{
	    item=new list<selectoption>();
	    item.add(new selectoption('myTasks','Tasks Assigned to Me'));
	    item.add(new selectoption('myDelegatedTasks','Tasks I Assigned to Others'));
	}
 
	public pagereference redirect()
	{
	     PageReference pageRef= new PageReference('/apex/'+picklistvalue);
	    pageRef.setredirect(true);
	    return pageRef;
	}

}

 

  • August 19, 2013
  • Like
  • 0

I have a trigger that will insert a feed item whenever an attachment is added to a record.  I've tried a few things to get a test class in place but am striking out.  Here is the trigger:

 

trigger attachmentTrigger on Attachment (after delete, after insert, after update) {
	
	if(trigger.isinsert) {
		for(Attachment a:trigger.new){
			//system.debug(a);
			feedItem f= new feedItem();
			f.ParentId=a.ParentId;
			f.Title=a.Name;
			//f.body=a.body;
			f.body=((Trigger.isInsert) ? 'New' : 'Updated') +'Attachment'+ ' '+ a.Name +' ' +'is added ';
			insert f;
			//system.debug('f.id--->'+f.id);
		}
	}	
	
	if(trigger.isdelete) {
		for(Attachment a:trigger.old){
			//system.debug(a);
			feedItem f= new feedItem();
			f.ParentId=a.ParentId;
			f.Title=a.Name;
			//f.body=a.body;
			f.body=((Trigger.isDelete) ? 'Attachment' : 'Deleted') + ' '+ a.Name +' ' +'is deleted ';
			insert f;
			//system.debug('f.id--->'+f.id);
		}
	}
}

 

Any help writing a test class would be hugely appreciated!

  • August 12, 2013
  • Like
  • 0

We currently have our opportunities set up as a self lookup in a parent/child relationship via a single Visual Force page.  They parent and child records are identified primarilly via record type.  For example when an opportunity is created, you have the ability to add products.  When saved, the opportunity information becomes the parent opportunity and the products added become the child opportunities.  Each of these child records (products) becomes a record in the opportunity object when saved.  

 

We did this so that we could track stages and probabilities for each product.

 

Owners of the opportunities currently add members to their Opportunity Team on the parent opportunity record.  This team infomation is then propagated to the child records via an Insert Trigger.

 

The problem is that, I also need to allow the same level of permission for the child records that exists on the parent record.  

 

Right now, setting a value of Read/Write on the parent will only create a value of "Read" for every child entry in the Opportunity Team Member object.  Here is the trigger code:

 

trigger syncOpportunityTeamMember on Opportunity (after insert) 
{
    Map<id,Id> projectChildOppMap = new Map<Id,Id>();
    
    for(Opportunity o:trigger.new)
    {
        if(o.Project_Opportunity__c!=null)
            projectChildOppMap.put(o.Id,o.Project_Opportunity__c);            
    }
    
    Set<Id> projOppIdSet = new Set<Id>();
    projOppIdSet.addAll(projectChildOppMap.values());
    
    Map<Id,List<OpportunityTeamMember>> oppTeamMemberMap = new Map<Id,List<OpportunityTeamMember>>();
    
    for(OpportunityTeamMember otm:[Select Id,UserId,OpportunityId,OpportunityAccessLevel,TeamMemberRole from OpportunityTeamMember where OpportunityId In:projOppIdSet])
    {
        List<OpportunityTeamMember> lst = oppTeamMemberMap.containsKey(otm.OpportunityId) ? oppTeamMemberMap.get(otm.OpportunityId):new List<OpportunityTeamMember>();
        lst.add(otm);
        oppTeamMemberMap.put(otm.OpportunityId,lst);                    
    }
    
    List<OpportunityTeamMember> lst2Insert = new List<OpportunityTeamMember>();
    
    for(Id oppId :projectChildOppMap.keySet())
    {
        if(projectChildOppMap.containsKey(oppId) && oppTeamMemberMap.containsKey(projectChildOppMap.get(oppId)))
        {
            for(OpportunityTeamMember otm:oppTeamMemberMap.get(projectChildOppMap.get(oppId)).deepClone())
            {
                otm.OpportunityId = oppId;
                lst2Insert.add(otm);    
            }
        }
    }
    
    if(lst2Insert.size()>0)
        insert lst2Insert;
}

 

  • July 08, 2013
  • Like
  • 0

I have a custom object that stores an association between multiple users and a task. (i.e. Users that want to be informed regarding any task updates)  The object has the User ID (lookup field) and the Task ID (Text Field)  I am trying to use a trigger to send an email "After Udpate" of a task to that list of users.

 

Three things concern me,

 

1) I need to be able to take the emails addresses of the users in the custom object and concatonate them together to place in the "toAddresses" line and send an email after the update of a Task they are associated with.  Currently with the code below, it returns the value (User:{Email=xxxxx@yyyyy.com, Id=005d0000001V9oSAAS}) for each individual instead of just the email address.  Everything else seems to work correctly.

 

2)  I need to be able to append the email address of the individual that created the task to the list and I haven't been able to do that effectively.

 

3)  I feel like my code is not clean and will cause issues with potential DML limits.  I can disable on any mass imports but I am worried about day to day usage bumping against govenor limits.

 

Thanks in advance for any help!

 

 

trigger SendEmailonTaskUpdate on Task (after update) { 
  
   	String taskId = ApexPages.currentPage().getParameters().get('Id');  
	
    List<Task_Informed_Users__c> emailList = New List<Task_Informed_Users__c>();
    emailList =  [Select Informed_User__c from Task_Informed_Users__c where Task_ID__c =: taskId];
    
	String taskCreatedByUser = [select Email from User where Id = :trigger.old[0].CreatedById].Email;
	
	String emailAddr = '';
	for (Integer i = 0; i < emailList.size(); i++) {
	
		If (emailAddr =='') {
				emailAddr = emailAddr + [Select Email from User Where Id=: emailList[i].Informed_User__c];
			} 
		Else 
			{
				emailAddr = emailAddr + '; ' + [Select Email from User Where Id=: emailList[i].Informed_User__c];
		}
	}
	
	If (emailAddr != 'null') {
		emailAddr = emailAddr + '; ' + taskCreatedByUser;
	} Else {
		emailAddr = taskCreatedByUser;
	}
	    
   	Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();     
        
    String[] toAddresses = new String[] {emailAddr};
    mail.setToAddresses(toAddresses);
    
    mail.setSubject('Details : ' + trigger.new[0].Subject + ' AND ' + trigger.new[0].Status);
    
    mail.setPlainTextBody('The details for Task: ' + trigger.new[0].Subject + ' have been changed.');
    mail.setHtmlBody('The details for Task: <b>' + trigger.new[0].Subject + '</b> have been changed </b>');   
   
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

 

 

 

 

  • June 14, 2013
  • Like
  • 0

I have an object with two fields.  One that is a text field that will contain a task ID and another that will contain a user Id.  I have a wrapper (thanks to the very excellent tutorials done by Bob Buzzard) that will build input fields dynamically in order to associate a user (via lookup field) who wants to be informed about a task with the task id (stored in an 18 char text field since for some crazy reason in the salesforce universe you can't create a lookup from a customer object to Tasks...)  (i.e. there will be a many to one relationship)

 

The code below does a great job of inserting the values in the custom object for the user info, however I need to grab the task ID from the URL and either 

 

1) propagate the ID value in a hidden visualforce field then try to pick it up in the save event and apply it to the list object - OR -

2) just reference the code from the custom controller and not worry about the visualforce code at all and apply it to the list object during the save event.

 

Here is the Visualforce:

 

<apex:page controller="ManageListController" tabstyle="Task">
	<apex:form >
		<apex:pageBlock title="Add Informed Users">
		
			<apex:pageBlockTable value="{!wrappers}" var="wrapper" id="wtable">        
				<apex:column headerValue="Name">
					<apex:inputField value="{!wrapper.iUsr.Informed_User__c}"/>
				</apex:column> 								
				<apex:column headerValue="Action">
					<apex:commandButton value="Delete" action="{!delWrapper}" rerender="wtable">
						<apex:param name="toDelIdent" value="{!wrapper.ident}" assignTo="{!toDelIdent}"/> 
					</apex:commandButton>
				</apex:column>
			</apex:pageBlockTable>
			
			<apex:commandButton value="Add Row" action="{!addRows}" rerender="wtable">
				<apex:param name="addCount" value="1" assignTo="{!addCount}"/> 
			</apex:commandButton>
			<apex:commandButton value="Add 5 Rows" action="{!addRows}" rerender="wtable">
				<apex:param name="addCount" value="5" assignTo="{!addCount}"/> 
			</apex:commandButton>
			<apex:commandButton value="Save" action="{!save}"/>
		</apex:pageBlock>
	</apex:form>
</apex:page>

 

 

Here is the code for the Apex controller:

 

public class ManageListController 
{
	public List<informedUserWrapper> wrappers {get; set;}
	public static Integer toDelIdent {get; set;}
	public static Integer addCount {get; set;}
	private Integer nextIdent=0;
	
		  
	public ManageListController()
	{
		wrappers=new List<informedUserWrapper>();
		for (Integer idx=0; idx<1; idx++)
		{
			wrappers.add(new informedUserWrapper(nextIdent++));
		}
	}
	


	public String getTaskId()
	{
		string taskId = ApexPages.currentPage().getParameters().get('retURL');
		return taskId;		
	} 
	
	
	
	public void delWrapper()
	{
		Integer toDelPos=-1;
		for (Integer idx=0; idx<wrappers.size(); idx++)
		{
			if (wrappers[idx].ident==toDelIdent)
			{
				toDelPos=idx;
			}
		}
	   
		if (-1!=toDelPos)
		{
			wrappers.remove(toDelPos);
		}
	}
	  
	  
	  
	public void addRows()
	{
		for (Integer idx=0; idx<addCount; idx++)
		{
			wrappers.add(new informedUserWrapper(nextIdent++));
		}
	}
	 
	 
	  
	public PageReference save()
	{
		List<Task_Informed_Users__c> iUsrs = new List<Task_Informed_Users__c>();		
				
		for (informedUserWrapper wrap : wrappers)
		{
			iUsrs.add(wrap.iUsr);
		
		}
	   
		insert iUsrs;
	   
		return new PageReference('/' + Schema.getGlobalDescribe().get('Task_Informed_Users__c').getDescribe().getKeyPrefix() + '/o');
	}
	 

	  
	  
	public class informedUserWrapper
	{
		public Task_Informed_Users__c iUsr {get; private set;}
		public Integer ident {get; private set;}
			  
		public informedUserWrapper(Integer inIdent)
		{
			ident=inIdent;			
			iUsr = new Task_Informed_Users__c();		
	  	}
	}
}

 

 

 

  • June 03, 2013
  • Like
  • 0

Our opportunity model utilizes parent and child opportunities that are stored on the same object with a self lookup of the parent opp on the child opp record.  There is a one to many relationship between parent (the project) and child (the products) opportunites.

 

I am trying to create a trigger that will take values from the Parent Opp and propagate them down to the child opp and am getting an error and can't quite figure it out.  Code below:

 

 

 

trigger updateChildOppParentValues on Opportunity (before update) {

Map<id,Opportunity> mapOpp = new map<id,Opportunity>([select id, StageName, CloseDate, AccountId, Cellular_Chipset__c, Configuration__c, Chipset_Provider__c,
Design_House__c, EAU__c, Lifetime_Volume_units__c, Market_Segment__c, Mass_Production_Date__c,
Probability, Program_Lifetime_mos__c, Region_Carrier__c, Amount, Wifi_Chipset__c
from Opportunity where id =: trigger.new]);

List<Opportunity> toUpdate = new list<Opportunity>();

For(Opportunity opp :[select id from Opportunity where Project_Opportunity__c =:trigger.new]) {
Error occurring on this line:  toUpdate.add(new Opportunity(id=opp.Id, Project_Cellular_Chipset__c = mapOpp.get(opp.id).Cellular_Chipset__c,Project_Chipset_Configuration__c=mapOpp.get(opp.id).Configuration__c,Project_Chipset_Provider__c=mapOpp.get(opp.id).Chipset_Provider__c,Project_Customer_Parent_Location__c=mapOpp.get(opp.id).Design_House__c,Project_Design_Win_Target_Date__c=mapOpp.get(opp.id).CloseDate,Project_EAU__c=mapOpp.get(opp.id).EAU__c,Project_Lifetime_Volume_units__c=mapOpp.get(opp.id).Lifetime_Volume_units__c,Project_Market_Segment__c=mapOpp.get(opp.id).Market_Segment__c,Project_Mass_Production_Date__c=mapOpp.get(opp.id).Mass_Production_Date__c,Project_Probability__c=mapOpp.get(opp.id).Probability,Project_Program_Lifetime_mos__c=mapOpp.get(opp.id).Program_Lifetime_mos__c,Project_Region_Carrier__c=mapOpp.get(opp.id).Region_Carrier__c,Project_Stage__c=mapOpp.get(opp.id).StageName,Project_Total_Value__c=mapOpp.get(opp.id).Amount,Project_WiFi_Configuration__c=mapOpp.get(opp.id).Wifi_Chipset__c));

}

If (toUpdate.size()>0) update toUpdate;

}

 

 

It's probably something really silly but any help would be appreciated!

  • April 25, 2013
  • Like
  • 0

Synopsis:

There is a checkbox on the account named 'Private Account'.  If a user creates an opportunity and the account they reference has Private Account set to TRUE, I want to force a boolean field on the Opportunity name 'Private Opportunity' to also be set to TRUE at the time the opportunity is created or edited.  If the account does not have 'Private Account' set to TRUE, the user should be able to set the 'Private Opportunity' field to TRUE or FALSE without any intervention on the part of the trigger.

 

I have tried 4-5 different ways to do this and haven't been able to get it to work correctly.  Currently code below:

 

trigger validateOppAccountSharing on Opportunity (before insert, before update) {
	
	List<Opportunity> objOpps = [Select Account.Private_Account__c From Opportunity Where Id in: Trigger.new];
	
	for (Integer i = 0; i < Trigger.new.size(); i++) {
		if (objOpps[i].Account.Private_Account__c == true) {
			trigger.new[i].Private_Opportunity__c == TRUE;
		}
	}
}

 Right now I am getting an error that the 'Expression cannot be a statement.'  In other words my syntax or method of assigning TRUE to 'Private_Opportunity__c' is incorrect.

 

Any help is appreciated.

  • September 25, 2013
  • Like
  • 0

So I've come to realize that there are two errors that I am learning to dislike very much...

1)  Easilly the one I dislike the most is:  "System.NullPointerException: Attempt to de-reference a null object"

2) The second has become:  Save error: Constructor not defined: [ApexPages.StandardController].<Constructor>(xxxxx)

 

I've just written a half dozen or more Test Classes using the same syntax for creating the constructor in my test method but for some reason, this one is giving me a fit.

 

This class is an extension class.  Is there something I need to do different? The constructors in all my classes are set up almost identically so I would assume creating them in my test class would be as well.

 

public with sharing class taskMyDelegatedView {
	
	public Id tskId {get;set;}	
	public Id uID {get;set;}
	public String iView {get;set;}
	
	
	private ApexPages.StandardController controller;
	public taskMyDelegatedView(ApexPages.StandardController stdController) {
      controller = stdController;
   }
	
	Id currentUserId = userinfo.getUserId();	
	   
	public List<Task> getMyDelegatedTasks() {
        return [SELECT id, Subject, Description, Status, WhatId, What.Name, Owner.Name, OwnerId, CreatedBy.Name, CreatedById, ActivityDate, Task_Due_Date__c, LastModifiedDate FROM Task WHERE CreatedById =: currentUserId ORDER BY LastModifiedDate];        
    }
    
   
   String result='Click on a task subject to preview the latest notes.';
   public String getFetchedData() {
   		return result;
   } 
   
   public PageReference invokeService() {
   		Id id = System.currentPageReference().getParameters().get('id');
   		result = [SELECT Description FROM Task WHERE Id=:id].Description;
   		return null;   	
   }
   

    public static Task testTsk;
    public static taskMyDelegatedView testTaskMDV;
    public static Task_Informed_Users__c testInformedUser;
    public static User testUserId;
        
    static testMethod void informedUserListTest() {    	
    	Test.startTest();    		
    		
	    	testUserId = [SELECT ID FROM User WHERE LastName=: 'User2'];
	    	System.Debug(testUserId);
	    	
	        testTsk = new Task(Subject='testTask', description='ABC', ownerId=testUserId.Id); 
	        insert testTsk;
	        System.Debug(testTsk.Id);	        
	       	        
	            
	        testInformedUser = new Task_Informed_Users__c(Informed_user__c=testUserId.Id, Task_ID__c=testTsk.Id, Chatter_Notification__c=FALSE, Send_Email__c=FALSE);
	        insert testInformedUser;
	        System.Debug(testInformedUser.Id);

	        
	        Test.setCurrentPage(Page.delegatedTaskView);
		ApexPages.currentPage().getParameters().put('Id',testTsk.Id);
			
		ApexPages.Standardcontroller con = new ApexPages.Standardcontroller(testTaskMDV); //ERROR HAPPENING HERE
		taskMyDelegatedView tTMDV = new taskMyDelegatedView(con);
	        
	        system.runas(testUserId) {
				

		}
        
        Test.stopTest();        
    }


}

 

  • September 10, 2013
  • Like
  • 0

I am trying to get better coverage of a particular controller extension and am having a few issues with one particular line.  I have a custom object where I store a task Id and a user Id and a few other fields.  This class is meant to query, insert, or delete records in that object.

 

In the getInformedUsers method below, all the lines test fine with the exception of the Return property.  I keep getting a Attempt to dereference a null object error.  The only other place where I can't seem to get coverage is in the removeInformed method for the redirect lines.  

 

I am currently at 61% pass if I do not test the getInformedUsers method but would love figure out how to cover that as well.  Code below:

 

public with sharing class informedUserList {
	
	private ApexPages.StandardController controller;
	
	
	public informedUserList(ApexPages.StandardController stdController) {     
      controller = stdController;
   }	   
	public List<Task_Informed_Users__c> getInformedUsers() {
		
		String tskID = ApexPages.currentPage().getParameters().get('Id');
		String longTaskId = String.valueOf(tskId);
		String shortTaskId = longTaskId.left(15);	
		     
        return [SELECT id, Informed_User__r.Name, Chatter_Notification__c, Send_Email__c FROM Task_Informed_Users__c WHERE Task_Id__c =: shortTaskId];
    }   
    
	public PageReference addInformed() {		
		string tskId = ApexPages.currentPage().getParameters().get('Id');		
		
		PageReference tskInformed = new pagereference('/apex/informedUsers?tId='+tskId);
		tskInformed.setRedirect(true);
  		return tskInformed;  			

	}

	public PageReference removeInformed() {		
		string tskId = ApexPages.currentPage().getParameters().get('Id');
		Id iuRecId = System.currentPageReference().getParameters().get('iuRec');
		
		delete [select id from Task_Informed_Users__c where ID=: iuRecId ]; 

   		return null;
		
		PageReference tskInformed = new pagereference('/apex/taskDetail?Id='+tskId);
		tskInformed.setRedirect(true);
  		return tskInformed;  			

	}
	
    
    public static Task testTsk;
    public static Task_Informed_Users__c testInformedUser;
    public static ID testTaskId;
    public static User testUserId;
        
    static testMethod void informedUserListTest() {    	
    	Test.startTest();
    	
    	testUserId = [SELECT ID FROM User WHERE LastName=: 'User2'];
        testTsk = new Task(Subject='testTask', ownerId=testUserId.Id); 
        insert testTsk;
        testTaskId = testTsk.Id;
            
        testInformedUser = new Task_Informed_Users__c(Informed_user__c=testUserId.Id, Task_ID__c=testTaskId, Chatter_Notification__c=FALSE, Send_Email__c=FALSE);
        insert testInformedUser;
        
        Test.setCurrentPage(Page.taskDetail);
		ApexPages.currentPage().getParameters().put('tId',testTaskId);         
              
        ApexPages.StandardController con = new ApexPages.StandardController(testInformedUser);
        informedUserList tInformedUserList = new informedUserList(con); 
        
        tInformedUserList.addInformed();  //Tests Fine
      
        tInformedUserList.removeInformed(); //Tests all but the redirect code    
        
        tInformedUserList.getInformedUsers();  //Get Attempt to DeReference a Null Object error
           
        
        Test.stopTest();        
    }
      
}

 

  • September 09, 2013
  • Like
  • 0

I am having trouble determining how to do this properly.    I have an Apex Class that has a list that is built based on a SOQL query into a custom object that contains Task IDs.  I want to use that list to iterate through the Task object to return the values below to another list object that is then referenced in a Visualforce data table by calling "{!getMyInformedTasks}". 

 

What is below just seems off in how it's constructed.  I am getting the error, "Save error: Variable does not exist: getMyInformedTasks"

 

 

        Id currentUserId = userinfo.getUserId();
	
	List<Task_Informed_Users__c> informedTaskList = [SELECT task_id__c FROM Task_Informed_Users__c WHERE informed_User__c =: currentUserId];
	
	public List<Task> getMyInformedTasks() {
		for(Task_Informed_Users__c tIU : informedTaskList) {
			for(Task t : tIU) {				
				getMyInformedTasks.add(t.Id);
				getMyInformedTasks.add(t.Subject);
				getMyInformedTasks.add(t.Description);
				getMyInformedTasks.add(t.Status);
				getMyInformedTasks.add(t.WhatId);
				getMyInformedTasks.add(t.What.Name);
				getMyInformedTasks.add(t.Owner.Name);
				getMyInformedTasks.add(t.OwnerId);
				getMyInformedTasks.add(t.CreatedBy.Name);
				getMyInformedTasks.add(t.CreatedById);
				getMyInformedTasks.add(t.ActivityDate);
				getMyInformedTasks.add(t.Task_Due_Date__C);							
			}
		}		
		return getMyInformedTasks;		
	}

 

  • August 19, 2013
  • Like
  • 0

I have a picklist that I am trying to generate from a class.  The idea is that when a user picks an item from the list that they will be redirected to the corresponding page.  When I use the code snippet below in a test page where the class is set as the "Controller=class" it works great.  However, when I add the class to another page as "extensions=class", the drop down list will not render any values.

 

Any ideas on how to get this to render properly.

 

Visualforce:

 

<apex:page standardController="Task" extensions="taskManagementRedirectPicklist" tabStyle="Task">
<apex:form >	
	<apex:pageBlock title="Selection Criteria">		
		
		<apex:pageBlockSection showHeader="false" title="Options" columns="3">
			<apex:pageBlockSectionItem >
				
				<apex:selectList value="{!picklistvalue}" size="1" >
			    	<Apex:selectOptions value="{!item}"/>
			    	<apex:actionSupport event="onchange" action="{!redirect}" />    
			    </apex:selectList>
			    		
			</apex:pageBlockSectionItem>
	    </apex:pageBlockSection>
	</apex:pageBlock>
</apex:form>
</apex:page>

 

Apex Class:

 

public with sharing class taskManagementRedirectPicklist {
	
	private ApexPages.StandardController controller;
	
	public taskManagementRedirectPicklist(ApexPages.StandardController stdController) {
      controller = stdController;
   }   
	
	public list<selectoption>item{get;set;}
	public string picklistvalue{get;set;}
	
	public taskManagementRedirectPicklist()
	{
	    item=new list<selectoption>();
	    item.add(new selectoption('myTasks','Tasks Assigned to Me'));
	    item.add(new selectoption('myDelegatedTasks','Tasks I Assigned to Others'));
	}
 
	public pagereference redirect()
	{
	     PageReference pageRef= new PageReference('/apex/'+picklistvalue);
	    pageRef.setredirect(true);
	    return pageRef;
	}

}

 

  • August 19, 2013
  • Like
  • 0

I have a trigger that will insert a feed item whenever an attachment is added to a record.  I've tried a few things to get a test class in place but am striking out.  Here is the trigger:

 

trigger attachmentTrigger on Attachment (after delete, after insert, after update) {
	
	if(trigger.isinsert) {
		for(Attachment a:trigger.new){
			//system.debug(a);
			feedItem f= new feedItem();
			f.ParentId=a.ParentId;
			f.Title=a.Name;
			//f.body=a.body;
			f.body=((Trigger.isInsert) ? 'New' : 'Updated') +'Attachment'+ ' '+ a.Name +' ' +'is added ';
			insert f;
			//system.debug('f.id--->'+f.id);
		}
	}	
	
	if(trigger.isdelete) {
		for(Attachment a:trigger.old){
			//system.debug(a);
			feedItem f= new feedItem();
			f.ParentId=a.ParentId;
			f.Title=a.Name;
			//f.body=a.body;
			f.body=((Trigger.isDelete) ? 'Attachment' : 'Deleted') + ' '+ a.Name +' ' +'is deleted ';
			insert f;
			//system.debug('f.id--->'+f.id);
		}
	}
}

 

Any help writing a test class would be hugely appreciated!

  • August 12, 2013
  • Like
  • 0

I have a visualforce page that I wamt to hook to a custom button on the Contact page layout.  When a user clicks on the button it will open the visualforce and display a list of records from a custom object that is related to a specific contact.

 

I setup the page using the standardController="Contact" and the extensions attribute...i.e. extensions="MyControllerExtension"

 

MyControllerExtension uses the StandardSetController so I can use pagination to page over the results, but I'm getting the error: Unknown constructor 'MyControllerExtension.MyControllerExtension(ApexPages.StandardController controller).

 

If I use the custom controller...i.e. controller="MyControllerExtension" then the visualforce page is not accessible to select as an option for the custom button.  How can I use the standardSetController in the my controller and still use the standardController from my VF page so I can hook the custom button to my page?

 

Thanks.

I have a custom object that stores an association between multiple users and a task. (i.e. Users that want to be informed regarding any task updates)  The object has the User ID (lookup field) and the Task ID (Text Field)  I am trying to use a trigger to send an email "After Udpate" of a task to that list of users.

 

Three things concern me,

 

1) I need to be able to take the emails addresses of the users in the custom object and concatonate them together to place in the "toAddresses" line and send an email after the update of a Task they are associated with.  Currently with the code below, it returns the value (User:{Email=xxxxx@yyyyy.com, Id=005d0000001V9oSAAS}) for each individual instead of just the email address.  Everything else seems to work correctly.

 

2)  I need to be able to append the email address of the individual that created the task to the list and I haven't been able to do that effectively.

 

3)  I feel like my code is not clean and will cause issues with potential DML limits.  I can disable on any mass imports but I am worried about day to day usage bumping against govenor limits.

 

Thanks in advance for any help!

 

 

trigger SendEmailonTaskUpdate on Task (after update) { 
  
   	String taskId = ApexPages.currentPage().getParameters().get('Id');  
	
    List<Task_Informed_Users__c> emailList = New List<Task_Informed_Users__c>();
    emailList =  [Select Informed_User__c from Task_Informed_Users__c where Task_ID__c =: taskId];
    
	String taskCreatedByUser = [select Email from User where Id = :trigger.old[0].CreatedById].Email;
	
	String emailAddr = '';
	for (Integer i = 0; i < emailList.size(); i++) {
	
		If (emailAddr =='') {
				emailAddr = emailAddr + [Select Email from User Where Id=: emailList[i].Informed_User__c];
			} 
		Else 
			{
				emailAddr = emailAddr + '; ' + [Select Email from User Where Id=: emailList[i].Informed_User__c];
		}
	}
	
	If (emailAddr != 'null') {
		emailAddr = emailAddr + '; ' + taskCreatedByUser;
	} Else {
		emailAddr = taskCreatedByUser;
	}
	    
   	Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();     
        
    String[] toAddresses = new String[] {emailAddr};
    mail.setToAddresses(toAddresses);
    
    mail.setSubject('Details : ' + trigger.new[0].Subject + ' AND ' + trigger.new[0].Status);
    
    mail.setPlainTextBody('The details for Task: ' + trigger.new[0].Subject + ' have been changed.');
    mail.setHtmlBody('The details for Task: <b>' + trigger.new[0].Subject + '</b> have been changed </b>');   
   
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

 

 

 

 

  • June 14, 2013
  • Like
  • 0

Our opportunity model utilizes parent and child opportunities that are stored on the same object with a self lookup of the parent opp on the child opp record.  There is a one to many relationship between parent (the project) and child (the products) opportunites.

 

I am trying to create a trigger that will take values from the Parent Opp and propagate them down to the child opp and am getting an error and can't quite figure it out.  Code below:

 

 

 

trigger updateChildOppParentValues on Opportunity (before update) {

Map<id,Opportunity> mapOpp = new map<id,Opportunity>([select id, StageName, CloseDate, AccountId, Cellular_Chipset__c, Configuration__c, Chipset_Provider__c,
Design_House__c, EAU__c, Lifetime_Volume_units__c, Market_Segment__c, Mass_Production_Date__c,
Probability, Program_Lifetime_mos__c, Region_Carrier__c, Amount, Wifi_Chipset__c
from Opportunity where id =: trigger.new]);

List<Opportunity> toUpdate = new list<Opportunity>();

For(Opportunity opp :[select id from Opportunity where Project_Opportunity__c =:trigger.new]) {
Error occurring on this line:  toUpdate.add(new Opportunity(id=opp.Id, Project_Cellular_Chipset__c = mapOpp.get(opp.id).Cellular_Chipset__c,Project_Chipset_Configuration__c=mapOpp.get(opp.id).Configuration__c,Project_Chipset_Provider__c=mapOpp.get(opp.id).Chipset_Provider__c,Project_Customer_Parent_Location__c=mapOpp.get(opp.id).Design_House__c,Project_Design_Win_Target_Date__c=mapOpp.get(opp.id).CloseDate,Project_EAU__c=mapOpp.get(opp.id).EAU__c,Project_Lifetime_Volume_units__c=mapOpp.get(opp.id).Lifetime_Volume_units__c,Project_Market_Segment__c=mapOpp.get(opp.id).Market_Segment__c,Project_Mass_Production_Date__c=mapOpp.get(opp.id).Mass_Production_Date__c,Project_Probability__c=mapOpp.get(opp.id).Probability,Project_Program_Lifetime_mos__c=mapOpp.get(opp.id).Program_Lifetime_mos__c,Project_Region_Carrier__c=mapOpp.get(opp.id).Region_Carrier__c,Project_Stage__c=mapOpp.get(opp.id).StageName,Project_Total_Value__c=mapOpp.get(opp.id).Amount,Project_WiFi_Configuration__c=mapOpp.get(opp.id).Wifi_Chipset__c));

}

If (toUpdate.size()>0) update toUpdate;

}

 

 

It's probably something really silly but any help would be appreciated!

  • April 25, 2013
  • Like
  • 0