• kathybb
  • NEWBIE
  • 110 Points
  • Member since 2010

  • Chatter
    Feed
  • 4
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 23
    Questions
  • 26
    Replies
I've run into a problem with my Test code for a Controller extension.  The error message I get is: Constructor not defined: [Test_Line_Edit_Extension].<Constructor>(ApexPages.StandardController).  I need to get this fixed so I can deploy it to production to enable me to get rid of code that somehow made it into Production without accompanying test code.  Here is my test code:
@istest
public class Test_Line_Edit_Extension 
{
	public static testmethod void Test_Line_Edit_Extension()
	{
        Order_Line_Item__c initLI = new Order_Line_Item__c();
        ApexPages.StandardController sc = new ApexPages.standardController(initLI);
        Test_Line_Edit_Extension ext1 = new Test_Line_Edit_Extension(sc);
        ext1.getRecord(initLI);
        
       	Product2 myProduct = [select id, ProductCode, Family, Description
    	from Product2 where productCode = 'K PSIP MSL' Limit 1];
		Order__c myOrder = new Order__c();
		List<Order__c>OrdersList = new List<Order__c>();
		List<Order_Line_Item__c> LIList = new List<Order_Line_Item__c>();
		Account testAccount = new Account(Name = 'KBB Test Account');
		insert testAccount;
        if(testAccount.id != null)
        {
			myOrder = new Order__c(Customer_Account__c = testAccount.id);
		
			for(integer x = 1; x< 10;x++)
			{
			Order_Line_Item__c myLineItem = new Order_Line_Item__c(Name = myProduct.productCode + x, Price_per_unit__c = x,
            Quantity__c = 3, Year_of_Contract__c = 2,Type_of_Sale__c = 'Renewal',Order_Number__c = myOrder.id);
			system.assertEquals(myProduct.name, 'K PSIP MSL');
			system.assertEquals(myProduct.productCode, myLineItem.Product__c);
            }
        }
    }
	

}

Here is the code I'm trying to test:
public with sharing class LineEditExtension {

    private final Order_Line_Item__c m_ext {get;set;}
    public Order_Line_Item__c currentLine {get;set;}
    public ApexPages.StandardController m_con {get;set;}
    public ApexPages.StandardController m_Gstd {get;set;}
    public string m_currentLineId {get;set;}    
   
    public LineEditExtension(ApexPages.StandardController stdController){ 
        m_ext = (Order_Line_Item__c)stdController.getRecord();
    }
    
    public PageReference SaveAndNew(){
        ApexPages.StandardController m_Gstd = new ApexPages.StandardController(m_ext);
        PageReference OrderPage = m_Gstd.save(); 
        m_currentLineId=m_Gstd.getId(); 
        PageReference returnPage = new PageReference('/a07/e');
        return returnPage;
    }                                          
}

And here's the page:
<apex:page standardController="Order_Line_Item__c" extensions="LineEditExtension">
    <apex:sectionHeader title="{!$ObjectType.Order_Line_Item__c.label} Edit" subtitle="{!Order_Line_Item__c.name}"/>
    <apex:form >
    <apex:pageBlock title="{!$ObjectType.Order_Line_Item__c.label} Edit" mode="edit">
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save"/>
            <apex:commandButton action="{!saveAndNew}" value="Save & New"/>
            <apex:commandButton action="{!cancel}" value="Cancel"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection showHeader="true" title="Information" columns="2">
            <apex:inputField required="true" value="{!Order_Line_Item__c.Product__c}"/>
            <apex:pageBlockSectionItem />
            <apex:pageBlockSectionItem />
            <apex:pageBlockSectionItem />
            <apex:inputField required="true" value="{!Order_Line_Item__c.Order_Number__c}"/>
            <apex:inputField value="{!Order_Line_Item__c.Length_of_Subscription__c}"/>
            <apex:pageBlockSectionItem />
            <apex:inputField value="{!Order_Line_Item__c.Year_of_Contract__c}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection showHeader="true" title="Details" columns="2">
            <apex:inputField value="{!Order_Line_Item__c.Quantity__c}"/>
            <apex:inputField value="{!Order_Line_Item__c.Type_of_Sale__c}"/>
            <apex:inputField value="{!Order_Line_Item__c.Price_per_Unit__c}"/>
            <apex:inputField value="{!Order_Line_Item__c.New_Money__c}"/>
            <apex:inputField value="{!Order_Line_Item__c.Renewal_Increase_money__c}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection showHeader="true" title="System Information" columns="2">
            <apex:pageBlockSectionItem />
            <apex:pageBlockSectionItem />
            <apex:inputField required="true" value="{!Order_Line_Item__c.Name}"/>
            <apex:pageBlockSectionItem />
        </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Any insight will save my sanity.
Thanks,
KathyBB
  • September 25, 2014
  • Like
  • 0
I am having trouble removing no-longer needed classes from my production org.  I am following the directions in knowledge Article 000006188, but when I go to deploy to production, the display shows Overwrite and has a grey background rather then the delete (or similar) in red.  The problem I'm trying to solve is that the classes I need to remove are garbage, with very low code coverage, which is making my overall code coverage 74% instead of 86%.  I am at my wit's end, and will be very thankful for any insight.
  • September 22, 2014
  • Like
  • 0
The error is: Failed to create createContainerMember for containerId=1dc5000000000lrAAA: This container member belongs to a container that currently has an unfinished save request with deploymentId=1drR00000001PF8. You may not modify any members in this container until it completes.: Metadata Container ID

I have waited for over 24 hours and it still comes up every time I try to save my Apex code.  What can I do to clear it out so I can save code again?  What does this mean or how can I avoid it  in the future.  

Thanks so much for any insight.  This has me dead in the road currently.

kathybb
  • September 21, 2014
  • Like
  • 1
I'm attempting to write a trigger that is kicked off by a workflow rule.  Suddenly, when I try to look at the log in the Developer Console there are a bunch of "Source for ... could not be loaded and no debug information in the Source window.  The ... is filled in with String, System, LIST, () parentheses, Database, etc.  When I make a correction and try to Save my code, I'm getting the "long-running Operation did not complete continuing in the background" box.  But when I look at the records, the trigger updated them as it is intended to do.

Can anyone tell me what's going on?  I need to finish the Test code for this trigger and get it deployed, and with no useful information in the Source pane of the console, this is going to be tricky, if not impossible.

Or can anyone suggest ways to get around using the Developer Console?

Thanks,
kathybb

The system is throwing this error:FATAL_ERROR System.QueryException: IN operator must be used with an iterable expression.

 

The Query string is: 

string findTestPOs = 'SELECT id, name,Finalized__c,PO_Notes__c,Status__c, Ship_to_location__c, Expedite__c, PO_Date__c, Total_Price__c,Category__c,SFDC_Purchase_Order__c.ownerID FROM SFDC_Purchase_Order__c WHERE id in :MyPOIdSet';
The lines throwing the error are:
List<SFDC_Purchase_Order__c>myNewPOs = new List<SFDC_Purchase_Order__c>();
myNewPOs = database.query(FindTestPOs);

 

I have 2 questions:

What can I do to fix this error?

How can a Set not be iterable?

 

This reallly has me puzzled.  This is keeping my Test  code from running to completion.

I really appreciate any insight anyone has. 

 

Thank you very much.

Kathybb

I'm stuck in a Test program.  I'm getting the 'Unexpected token ']' on an attempt at a Set Constructor.  Here's the relevant code:

string noteString = 'KBB Test PO';
        Set<Id> findPOIds = new Set<id>([select id from SFDC_Purchase_Order__c where PO_Notes__c.contains(noteString)]);
        List<string> POIdList = database.query(findPOIds);
        string findTestPOs = [SELECT id, name,Finalized__c,PO_Notes__c,Status__c, Ship_to_location__c, Expedite__c, PO_Date__c, Total_Price__c,Category__c,SFDC_Purchase_Order__c.ownerID FROM SFDC_Purchase_Order__c WHERE id in (:POIdList)];
       	string findTestPRs = [SELECT id, OwnerId, CreatedBy.id, CreatedBy.Name,name, new_Item_Description__c, Status__c,Request_Date__c,Receive_by_Date__c,Quantity__c,Item_Requested__r.name,Department__c, Item_Requested__r.Price_per_Unit__c, Extended_Price__c,Purchase_Order__r.id FROM SFDC_Purchase_Requisition__c WHERE Purchase_Order__r.id in (:POidList)];
        List<SFDC_Purchase_Order__c>myNewPOs = new List<SFDC_Purchase_Order__c>((List<SFDC_Purchase_Order__c>)database.query(findTestPOs)); 
		List<SFDC_Purchase_Requisition__c>myNewPRs = new List<SFDC_Purchase_Requisition__c>((List<SFDC_Purchase_Requisition__c>)database.query(findTestPRs));		

 I have a couple of questions -- Why won't this compile? , What do I need to do to fix it? and -- How can the  right bracket be unexpected when it seems fine with the left bracket?

 

I'm very grateful for any insight anyone can offer

Thanks a lot.

Karhybb

I'm sure there is a simple answer to my question, but so far I haven't found it.  I have a Status__c  field that is a picklist.  Some of the entries have more than one word e.g. Sent to Purchaser.  I'm needing a query string declared early on and reused a couple of times.  Her's my latest attempt:

 

public string m_requestQuerybyStatus= [SELECT id, OwnerId, CreatedBy.id, name, new_Item_Description__c, Status__c,Request_Date__c,Receive_by_Date__c,Quantity__c,Item_Requested__r.name,Department__c, Item_Requested__r.Price_per_Unit__c, Extended_Price__c,Purchase_Order__r.id FROM SFDC_Purchase_Requisition__c WHERE (isBlank(Purchase_Order__c)= True) AND (ISPICKVAL(Status__c) = Sent to Purchaser) Limit 50];

The red clause is what is giving me trouble.  I've tried surrounding the sent to purchaser with all kinds of punctuation around it to no avail.  Either it gives an unkinown token: 'Sent' error, or it compiles fine and throws an SOQL query error when I try to run it.

 

Can anyone tell me what I'm doing wrong, or suggest things to try?

 

Thank you in advance for your time and help.

 

Kathybb

  • September 27, 2013
  • Like
  • 0

I have a requirement to render a visualforce page in PDF and attach it to the relevant Purchase Order (custom Object).  Here is my visualforce code:

<apex:page standardController="SFDC_Purchase_Order__c" renderas="PDF" extensions="AttachPRTOPOExtension" sidebar="false" showHeader="false" name="PDFPO">
    <br />
    <br />
    <center><big><big><br /> Broadcast Interactive Media</big></big></center><br/>
    <apex:outputPanel id="POInfo" layout="Block" style="font:Arial font-size: 9pt">
    <apex:outputtext value="Purchase Order Number:  " />
        <apex:outputField value="{!SFDC_Purchase_Order__c.Name}"/>
        <br />
        <apex:outputtext value="Date:  " />
        <apex:outputField value="{!SFDC_Purchase_Order__c.PO_Date__c}"/><br/>
        <apex:outputtext value="Purchase Order Status:  " />
        <apex:outputField value="{!SFDC_Purchase_Order__c.Status__c}"/><br/>
        <br />
        <apex:outputtext value="Deliver To:  " />
        <apex:outputField value="{!SFDC_Purchase_Order__c.Ship_To_Location__c}"/>
        
        <br />
        <br />
    </apex:outputPanel>
      
    <apex:dataTable value="{!m_displayResultList}" var="r" border="1px" cellpadding="2px" cellspacing="2px" width="100%" style="font:Arial fontsize=7pt">
        <apex:column width="10%" headerValue="Req #" value="{!r.name}" />
        <apex:column width="10%" headerValue="Requested For" value="{!r.createdby.name}"/>
        <apex:column width="10%" headerValue="Date" value="{!r.Request_Date__c}"/>
        <apex:column width="10%" headerValue="Quantity" value="{!r.Quantity__c}" />
        <apex:column width="10%" headerValue="Item Requested" value="{!r.item_Requested__r.name}" />
        <apex:column width="10%" headerValue="Price" value="{!r.item_requested__r.Price_per_unit__c}" />
        <apex:column width="10%" headerValue="Ext. Price" value="{!r.Extended_Price__c}" />
        <apex:column width="10%" headerValue="Needed by" value="{!r.Receive_by_Date__c}" />
    </apex:dataTable>
    
    
</apex:page>

 And here are the relevant method from my controller extension:

public PageReference ViewPDF()
    {   
        system.debug('*************************START VIEWPDF******************************');
        system.debug('m_currentId = '+m_currentId);
        List<SFDC_Purchase_Requisition__c> m_reqResultList = new List<SFDC_Purchase_Requisition__c>();
        List<SFDC_Purchase_Requisition__c> m_displayResultList = new List<SFDC_Purchase_Requisition__c>();
        PageReference retPDF = new PageReference('/apex/PDFPO?id='+m_currentId);
        system.debug('m_myPO = '+ m_myPO);
        string PDFqueryPO = 'select Name, CreatedBy.name, Ship_To_Location__c,Expedite__c,PO_Date__c, Owner.id, Total_Price__c, PO_Notes__c from SFDC_Purchase_Order__c where Id = :m_currentId Limit 1';
        
        SFDC_Purchase_Order__c PDFPO = new SFDC_Purchase_Order__c();
        PDFPO =(SFDC_Purchase_Order__c)database.query(PDFqueryPO);
        string PDFReqResultListquery = m_RequestQueryByPOid;
        m_reqResultList= database.query(PDFReqResultListquery);
        for(SFDC_Purchase_Requisition__c thisReq : m_reqResultList){
            system.debug('thisReq.name = '+ thisReq.name);
            system.debug('thisReq.createdby.name = '+ thisReq.createdby.name);
                        system.debug('thisReq.Request_Date__c) = '+ thisReq.Request_Date__c);
                        system.debug('thisReq.quantity__c = '+ thisReq.quantity__c);
                        system.debug('thisReq.item_requested__r.name = '+ thisReq.item_requested__r.name);
                        system.debug('thisReq.item_requested__r.price_per_unit__c = '+ thisReq.item_requested__r.price_per_unit__c);
            system.debug('thisReq.extended_price__c = '+ thisReq.extended_price__c);
            system.debug('thisReq.receive_by_date__c = '+ thisReq.receive_by_date__c);
        m_displayResultList = new List<SFDC_Purchase_Requisition__c>();
        For(SFDC_Purchase_Requisition__c x : m_reqResultList)
        {
            if(x != null){
            x = (SFDC_Purchase_Requisition__c)x;
            m_displayResultList.add(x);
            system.debug('x='+x);
            system.debug(m_displayResultList.size());
            }
        }
        }
        m_PDFPage = attach();
        system.debug('about to return m_PDFPage from ViewPDF = '+ m_PDFPage);
        return m_PDFPage;
    }
      
    public PageReference attach() 
    {
        system.debug('********************************START ATTACH**********************');
         system.debug('m_currentId = '+m_currentId);
        Attachment myAttach = new Attachment();
         system.debug('m_currentId = '+m_currentId);
        myAttach.ParentId = m_currentId;    //Id of the object to which the page is attached
        if(m_myPO != null)
        {
            string myFileName = (m_myPO.name + ' - '+ date.TODAY() + '.PDF');
            myAttach.name = myFileName;
            myAttach.description = 'BIM Purchase Order Summary for '+ m_myPO.name +' Created on '+ date.Today() +' by '+ m_myPO.CreatedBy.name;
            PageReference myPdf = new PageReference('/apex/PDFPO?id=' + m_currentID);
                myAttach.body = myPdf.getContentAsPdf();
            try 
            {
                database.SaveResult sra = database.insert(myAttach);
                if(sra.issuccess() == true)
                {
                m_currentAttachId = sra.getID();
                }
                else
                {
                    // Operation failed, so get all errors                
                    for(Database.Error err : sra.getErrors()) 
                    {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Attachment fields that affected this error: ' + err.getFields());
                    } 
                } 
            } catch(Exception e){
                system.debug('Creation of PDF Failed');
                system.debug('Message was: '+ e);
        }
    }
        system.debug('about to return m_PDFPage from attach = '+ m_PDFPage);
        return m_PDFPage;
    }

 The debug statements confirm that the list is populated correctly, but when the page renders, it displays properly down to the header row on the table and is blank for the rest of the table.  I would be very grateful if someone could point out what I am doing wrong.  The attach method works perfectly, but the table data is missing every time.

 

Thanks in advance for any insight.

 

kathybb

I'm writing a method to create a PDF Purchase Order and add it as an attachment to the PO record (custom object).

Here's the relavent apex code:

 

 public PageReference ViewPDF()
    {      
        system.debug('m_currentId = '+m_currentId);
        List<SFDC_Purchase_Requisition__c> m_reqResultList = new List<SFDC_Purchase_Requisition__c>();
        PageReference retPDF = new PageReference('/apex/PDFPO?id='+m_currentId);
        system.debug('m_myPO = '+ m_myPO);
        string PDFqueryPO = 'select Name, CreatedBy.name, Ship_To_Location__c,Expedite__c,PO_Date__c, Owner.id, Total_Price__c, PO_Notes__c from SFDC_Purchase_Order__c where Id = :m_currentId Limit 1';
        
        SFDC_Purchase_Order__c PDFPO = new SFDC_Purchase_Order__c();
        PDFPO =(SFDC_Purchase_Order__c)database.query(PDFqueryPO);
        string PDFReqResultListquery = m_RequestQueryByPOid;
        m_reqResultList= database.query(PDFReqResultListquery);
        m_displayResultList = new List<SFDC_Purchase_Requisition__c>();
        For(SFDC_Purchase_Requisition__c x : m_reqResultList)
        {
            if(x != null){
            x = (SFDC_Purchase_Requisition__c)x;
            m_displayResultList.add(x);
            }
           m_PDFPage = attach();
        }
        return m_PDFPage;
    }
      
    public PageReference attach() 
    {
         system.debug('m_currentId = '+m_currentId);
        Attachment myAttach = new Attachment();
         system.debug('m_currentId = '+m_currentId);
        myAttach.ParentId = m_currentId;    //Id of the object to which the page is attached
        if(m_myPO != null)
        {
            string myFileName = (m_myPO.name + ' - '+ date.TODAY() + '.PDF');
            myAttach.name = myFileName;
            PageReference myPdf = new PageReference('/apex/PDFPO?id=' + m_currentID);
            
            
            myAttach.body = myPdf.getContentAsPdf();
            try 
            {
                database.SaveResult sra = database.insert(myAttach);
                if(sra.issuccess() == true)
                {
                m_currentAttachId = sra.getID();
                }
                else
                {
                    // Operation failed, so get all errors                
                    for(Database.Error err : sra.getErrors()) 
                    {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Attachment fields that affected this error: ' + err.getFields());
                    } 
                } 
            } catch(Exception e){
                system.debug('Creation of PDF Failed');
                system.debug('Message was: '+ e);
        }
    }
        return m_PDFPage;
    }

 And here's the visualforce page 

 

<apex:page standardController="SFDC_Purchase_Order__c" extensions="AttachPRTOPOExtension" name="PDFPO" renderAs="PDF" action="{!ViewPDF}">
	<apex:outputPanel id="POInfo" layout="Block" style="font:Arial font-size: 9pt">
		<apex:outputField value="{!SFDC_Purchase_Order__c.Name}"/>
		<br />
		<apex:outputField value="{!SFDC_Purchase_Order__c.PO_Date__c}"/>
		<apex:outputField value="{!SFDC_Purchase_Order__c.Status__c}"/>
		<br />
		<apex:outputField value="{!SFDC_Purchase_Order__c.Ship_To_Location__c}"/>
		<apex:outputField value="{!SFDC_Purchase_Order__c.Expedite__c}"/>
		<br />
        <br />
	</apex:outputPanel>     
	<apex:DataTable value="{!m_displayResultList}" var="r" border="1px" cellpadding="1px" cellspacing="2px">
		<apex:column width="10%" headerValue="Request" value="{!r.name}" />
		<apex:column width="10%" headerValue="Requested By" value="{!r.Createdby.name}"/>
		<apex:column width="10%" headerValue="Request Date" value="{!r.CreatedDate}"/>
		<apex:column width="10%" headerValue="Quantity" value="{!r.Quantity__c}" />
		<apex:column width="10%" headerValue="Item Requested" value="{!r.Item_Requested__r.Name}" />
		<apex:column width="10%" headerValue="Price" value="{!r.Item_Requested__r.Price_per_unit__c}" />
		<apex:column width="10%" headerValue="Extended Price" value="{!r.Extended_Price__c}" />
		<apex:column width="10%" headerValue="Receive-by Date" value="{!r.Receive_by_Date__c}" />
	</apex:DataTable>
	<apex:relatedList list="Purchase_Requisitions__r" Title="Requisitions connected with this PO"/>
     <apex:relatedList list="NotesandAttachments" Title="Notes and Attched PDF PO"/>
</apex:page>

 I'm compiling it as version 25, to avoid the bug earlier reported to Salesforce.  

 

Can someone explain what I'm doing wrong in my controller extension?  This is the first time I've tried to generate a PDF file and attach it to a record, so any insight would be very appreciated.

Thanks in advance.

 

We have Chatter only licenses in our org.  The documentation says that they come with access to 10 custom objects, but when I try to add custom objects to their profile, the objects section is disabled.  Can anyone tell me how access to custom objects should be configured for Chatter Only users?

 

Thanks,

Kathy

I'm trying to write a test class, but I keep getting this error message.  Here's my code:

@isTest
public class Test_AttachPRTOPOExtension_Final{
    static testmethod void Test_Attachment_process() {
        SFDC_Purchase_Order__c myOrder = new SFDC_Purchase_Order__c();
        List<SFDC_Purchase_Requisition__c> RequestsToUpdate = new List<SFDC_Purchase_Requisition__c>();
        List<SFDC_Purchase_Items__c> ItemsToUpdate = new List<SFDC_Purchase_Items__c>();
        //Instatiate Controllers
        
        ApexPages.StandardController con = new ApexPages.StandardController(myOrder);
        AttachPRTOPOExtension ext = new AttachPRTOPOExtension(con);
          
        // create items
        List<SFDC_Purchase_Items__c> newItems= new List<SFDC_Purchase_Items__c>();
        for(integer i=0;i<100;i++){
            SFDC_Purchase_Items__c thisitem = new SFDC_Purchase_Items__c(name ='item '+ i);
            newItems.add(thisItem);
        }	//end for
        if(newItems.size() != 100){
            system.debug('newItems <> 100'+ newItems.size());
                } else {		//end if
        system.assertEquals(newItems.size(),100);
                }		// end else
        try {
            Database.SaveResult[] sriList = database.insert(newItems);
            for (Database.SaveResult sri : sriList) {
    			if (sri.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted item. Item ID: ' + sri.getId());
    } else {
        // Operation failed, so get all errors                
        for(Database.Error err : sri.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Item fields that affected this error: ' + err.getFields());
        }		// end inner for
    }			// end else
}				// 3ne outer for
        } catch (DMLEXCEPTION e){
            system.debug('insertItems failed: ' + e);
                         }	//end catch
		List<SFDC_Purchase_Order__c> newOrders = new List<SFDC_Purchase_Order__c>();
        date newDate= date.today();
        ID myPurchaser = [select id from User where  has_purchasing_authority__c = true Limit 1] ;
        ID myApprover = [select id from User where (has_approval_authority__c = true) and (has_purchasing_authority__c = false) Limit 1] ;
        List<SFDC_Purchase_Requisition__c> newReqs= new List<SFDC_Purchase_Requisition__c>();
       
        for(integer i=0;i<100;i++){
            SFDC_Purchase_Requisition__c thisReq = new SFDC_Purchase_Requisition__c(status__c = 'Sent to Purchaser',Department__c = 'Dev CR',Quantity__c = i,
                Item_requested__c = newItems[i].id, Approver__c = myApprover, Purchaser__c = myPurchaser); 
            newReqs.add(thisReq);
        }
        if(newReqs.size() != 100){
            system.debug('newIReqs <> 100'+ newReqs.size());
                } else {
        system.assertEquals(newReqs.size(),100);
                }
        Set<string> ReqSet = new Set<string>();
           try {
            Database.SaveResult[] srrList = database.insert(newReqs);
            for (Database.SaveResult srr : srrList) {
    if (srr.isSuccess()) {
        ReqSet.add(srr.getId());
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted Requisition. Requisition ID: ' + srr.getId());
    } else {
        // Operation failed, so get all errors                
        for(Database.Error err1 : srr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Requisition fields that affected this error: ' + err.getFields());
        }		//end inner for
    }		//end else
}			// end  outer for
        } catch (DMLEXCEPTION e){
            system.debug('insertReqs failed: ' + e);
        }
         List<SFDC_Purchase_Requisition__c> AllReqs = new List<SFDC_Purchase_Requisition__c>(AttachPRTOPOExtension.m_requestQuery);               }

        // create Orders

        

    for(integer o=0;o < 20; o++){
            SFDC_Purchase_Order__c anOrder = new SFDC_Purchase_Order__c(PO_notes__c = 'note number '+ o, Ship_To_Location__c= 'Cedar Rapids Office',
                                                                        Category = 'Dev CR', Expedite= true,
                                                                        PO_Date__c = newDate);
            newOrders.add(anOrder);
        }
    Test.startTest();
    	Set<string> OrderSet = new Set<string>();
        integer placeInList = 0;
        for(myOrder : newOrders){
            OrderSet.add(myOrder.id);
            myOrder = (SFDC_PurchaseOrder__c)myOrder;
            holdPage = SavePO();
            if(holdPage.URLfor = AttachPRTOPOExtension.m_DetailPage.urlFor){
                AssertNotEquals(AttachPRTOPOExtension.m_currentID, null);}
                AssertNotEquals(AttachPRTOPOExtension.m_resultList.size(), 0);
                for(AttachPRTOPOExtension.tempPR myReq : AttachPRTOPOExtension.m_resultList){
                    myReq = (AttachPRTOPOExtension.tempPR)myReq;
                    for(x=PlaceInList : x<PlaceInList+5 :x++){
                        myReq.selected = true;
                    }
                    PlaceInList++; 
                    AttachPRTOPOExtension.processSelected();
                    AssertEquals(AttachPRTOPOExtension.m_resultList.size(),5);
                    holdPage=AttachPRTOPOExtension.FinalizePO();
                    AssertEquals(ApexPage.currentPage().getURL(),AttachPRTOPOExtension.m_DetailPageROURL + AttachPRTOPOExtension.m_currentId)
                        }  //end inner for
						
                }  //end outer for
            Test.stoptest();
    List<SFDC_Purchase_Order__c> checkPOs = new List<SFDC_Purchase_Order__c>([select id,name,PO_Notes__c,
                                                                    PO_Date__c,Category__c, numRequisitions__c,
                                                                    Total_Price__c, Status__c,Ship_To_Location__c,
                                                                    Expedite__c, Finalized__c from
                                                                    Purchase_Order__c where id in OrderSet];
                                                                             for(SFDC_Purchase_Order__c myOrder : checkPOs){
                                                                                 AssertEquals(Status__c,'Placed');
                                                                                 AssertEquals(Finalized__c,'Placed');
                                                                                 AssertEquals(numRequisitions, 5);
                                                                                 AssertEquals(Expedite, false);
                                                                             }
    List<SFDC_Purchase_Requisitions__c> checkPRs= new List<SFDC_Purchase_Requisitions__c>([select Department__c,
                                                                                            Status__c,Approver__c,
                                                                                            Purchaser__c, Purchase_Order__c,
                                                                                            Quantity__c,Price_per_Unit__c,
                                                                                            Expedite__c,Editable__c,Finalized__c,
                                                                                            Item_Requested__c from SFDC_Purchase_Requisitions__c 
                                                                                            where id in ReqSet Order by Purchase_Order__c Limit 100]);
                                                                             for(SFDC_Purchase_Requisitions__c myReq : checkPRs){
                                                                                 AssertEquals(Status__c,'Sent to Purchaser');
                                                                                 AssertEquals(Finalize__c,true);
                                                                                 AssertEquals(Editable__c, false);
                                                                                 AssertEquals(Expedite__c, false);
                                                                                 AssertNotEquals(Price_per_unit__c, 0);
                                                                                 AssertNotEquals(Quantity__c, 0);
                                                                             }		//end for
																			 }		// end Class

 I've scoured the code to find the (apparent) unmatched curly bracket, with no joy, so I'm probably doing something else wrong which is messing with the compiler.  If I put a right curly bracket on line 82, as would be obvious, it matches up with the bracket at the start of the class, the message becomes "unexpected token: for" which makes sense as it would be appearing after the bracket ending the class definition.  Can anyone offer suggestions about what is wrong and how to fix it?

Thanks in advance.

I'm using a standard Controller's save action (called by sc.save()) to save a new record.  It returns a PageReference called OrderPage.  When I look at the returned PageReference in the debugger, it is the ID of the saved record preceded by a '/'.  I need to assign the id (without the '/' to a variable for further processing.  The page hasn't loaded, and in any event OrderPage.getParameters().get('id) doesn't work nor does (getting desperate here) OrderPage.valueOf() or various attempts at using string functions to extract it.

 

Can anyone tell me how to do this?  It seems like it would be a common use case, but a lot of searching both here and on the Internet has been unsuccessful.

 

I appreciate any help anyone can offer.

I'm trying to write a version of the Requisitions App from AppExchange.  It involves 3 custom objects (Purchase Items, Purchase Requisitions and Purchase Orders.)  I'm trying to write the part that updates certain Purchase Requisitions with the PO Number that they are ordered on.  I'm having trouble initializing my Test of the Extension code.  What I've got so far is:

public class Test_AttachPRTOPOController{
    static testmethod void Test_Attachment_process() {
        SFDC_Purchase_Order__c myPO = new SFDC_Purchase_Order__c();
       
		ApexPages.StandardController sc = new ApexPages.standardController(myPO);
        AttachPRTOPOController myPageCon = new AttachPRTOPOController(sc);

        List<SFDC_Purchase_Items__c> items = new List<SFDC_Purchase_Items__c>();
        string q1 = 'SELECT Id,Name FROM SFDC_Purchase_Items__c limit 1';
        items = database.query(q1);
        system.debug(q1);
        system.debug(items.size());
        if(items != null){
            for(SFDC_Purchase_Items__c thisItem : items){
                thisItem = (SFDC_Purchase_Items__c)thisItem;
                system.debug(thisItem.name + ' was created');
                system.assertNotEquals(thisItem,Null);
            }
        }                                          
            //create purchase requisitions
    }       
        
}

 I'm obviously doing something wrong because the query for Purchase_Items__c is returning null.  I can't really proceed with creating the rest of my test data until I can get hold of some Item records, and this is driving me crazy.  I can attach the Extension Code and pages, if needed, but it is rather long.

 

Thanks in advance for any insight.

 

Kathy (obvous Apex novice)

 

I'm attempting to code a list and I have the above error showing up whenever i attempt to compile the class.  Can anyone spot what Is wrong and tell me how to fix it?

 

Here's my page:

<apex:page standardController="SFDC_Purchase_Order__c" extensions="AttachPRTOPOController" action="{!initList}">
    <apex:form >
        <apex:pageBlock tabStyle="SFDC_Purchase_Order__c" >
             <apex:pageBlockTable value="{!resultList}" var="r"
                        id="resultsBlock" columns="9" width="20%">
                    // rendered="{!NOT(ISNULL(resultList))}">
                        <apex:column headerValue="PR No." width="5%">
                            <apex:outputLink value="/{!r.id}?retURL={$currentPage.URL}">{!r.Name}</apex:outputLink>
                        </apex:column>
                        <apex:column value="{!r.status__c}"
                            headerValue="Status" width="5%" />"
                        <apex:column value="{!r.status__c}"
                            headerValue="Type" width="10%" />
                        <apex:column value="{!r.RecordType__c}"
                            headerValue="Item" width="5%" />
                        <apex:column value="{!r.Item_Requested__c}"
                            headerValue="new Item Description" width="15%" />
                        <apex:column value="{!r.New_Item_Description__c}"
                            headerValue="Quantity" width="15%" />
                        <apex:column value="{!r.Quantity__c}"
                            headerValue="Requested By" width="10%" />
                        <apex:column value="{!r.CreatedDate}" headerValue="Created On"
                            width="10%" />
                        <apex:column value="{!r.CreatedBy.name}" headerValue="Requested By"
                            width="15%" />
                    </apex:pageBlockTable>
                </apex:pageBlock>
            </apex:form>
</apex:page>

 and here is my class:

public with sharing class AttachPRTOPOController {
     
    private final SFDC_Purchase_Order__c myPO;
    public final string myUser = UserInfo.getUserID();
    public final PageReference myParentPage = ApexPages.currentPage();
    public List<tempPR> resultList {get;set;}
    public List<SFDC_Purchase_Requisition__c> castRequestList {get; set;}
   	public AttachPRTOPOController(ApexPages.StandardController con) {
        this.myPO = (SFDC_Purchase_Order__c)con.getRecord();
       }
   
    public PageReference initList(){
       
        if(resultList == null  || resultList.size()<1) {
            resultList = new List<tempPR>();
        }
        System.debug('*************************************************starting InitList resultList = ' + resultList.size());
            string inputVar = ApexPages.currentPage().getParameters().get('id');
            System.debug('*************************************************************************************************Inside initList now');
             string qry = 'SELECT id, Name, Department__c, Status__c,RecordType Request_Date__c,SFDC_Purchase_Requisition__r.Item_Requsted__c, New_Item_Description__c,' 
                 + 'Quantity__c from SFDC_Purchase_Requisition__c where Purchaser__c.id = :myUser order by name asc limit 200';
            castRequestList = Database.query(qry);
            System.debug('castAccountList = ' + castRequestList + 'size = ' + castRequestList.size());
           
            for(SFDC_Purchase_Requisition__c myPR :  castRequestList) {
                resultList.add(new tempPR(myPR));
                System.debug('**********************************************************************************Building castAccountList myPR = ' + myPR);
             }
        return null;
    }
    
    public List<tempPR> getRequests() {
        if(resultList == null) {
            System.debug('**********************************************************************************************Inside getAccounts resultList = null');
                initList();
        }else{
            resultList.clear();
         }
       System.debug('**************************************************************************************resultList returned from getAccounts' + resultList);
        return resultList;
    }

    public PageReference processSelected() {
        System.debug('****************************************************************************************************Entered processSelected');
        
        for(tempPR tPR : getRequests()) {
            if(tPR.selected) {
                system.debug('******************************************at selectedAccount constructed: ' + tPR);
                system.debug('******************************************resultList = ' + resultList);
                resultList.add(tPR);
            }
         }
        return null;
    }
           
       public class tempPR {
            public SFDC_Purchase_Requisition__c request {get; set;}
            public Boolean selected {get; set;}

        public tempPR() {
        }

        public tempPR(SFDC_Purchase_Requisition__c req1) {
            request = req1;
            selected = false;
            
        }
    }
    
}

 Since I'm not very experienced, I know there are probably other problems with my code, but this is the one I'm having no luck in solving on my own.  I've tried replacing the quotes in the <apex:page> code with single quotes (didn't work, of course, since visualforce requires the double  quotes) and using a plain text editor to insert double quotes (char 34) over the double quotes that are there. I would be very grateful for any help anyone can offer.

 

Thank you in advance,

kathybb

:

 

I have a page with data from a custom object that I embedded in the Accounts page.  Can someone suggest a way to get more than 44% coverage in my code?  Here is may page, Controller extension, and Test code.  When I run the code through the UI (by calling up an account record), it appears to be working perfectly, which it should not if it isn't going into the "uncovered" lines.  I'd really appreciate any insight anyone has.

 

The Test Code

 

@isTest
private class TestSalesTargetsController {
    static  testMethod void TestSalesTargets() {
    Set<ID> newTargets = new Set<ID>();
    Account myAcct = new Account();
    Set<ID> ParentAccounts = new Set<ID>();
        
        
    ApexPages.StandardController con = new ApexPages.Standardcontroller(myAcct);
    SalesTargetsController ext = new SalesTargetsController(con);
   
    Account testAcctWithTargets= new Account();
      Account testAcctWithNoTargets = new Account();
      Sales_Targets__c testTargetwithData = new Sales_Targets__c();
      Sales_Targets__c testTargetNoData= new Sales_Targets__c();
      List<Account> AcctsToInsert = new List<Account>();
      List<Sales_Targets__c> TargetsToInsert= new List<Sales_Targets__c>();
   
// create Accounts for Testing
    for(integer x = 0;x<2;x++){
        system.debug('Account = ' + testAcctWithTargets);
        testAcctWithTargets = new Account(Name='TestAcctWithTargets' + x);
        AcctsToInsert.add(testAcctWithTargets);
        testAcctWithNoTargets = new Account(Name='TestAcctWithNoTargets' + x);
        AcctsToInsert.add(testAcctWithNoTargets);
    }
        try{
            Database.SaveResult[] results= Database.insert(AcctsToInsert, false);
            if(results != null)
                for(Database.SaveResult result : results){
                   
                    if(result.isSuccess()){
                        system.debug(result.getId());
                    ParentAccounts.add(result.getId());
                    }
                }
        }catch (DMLException e) {
            system.debug('Account Insert Failed with exception ' + e);
        }
    	
        
        // query Accounts for SalesTargets
        string accountQuery = 'select id, name from account where id in :ParentAccounts';
        
        Map<id, Account> MapAcc = new Map<id, Account>((List<Account>)Database.query(accountQuery));
        
        
        if(MapAcc == null) {
            system.debug('MapAcc has no records and is null');
        } else {
           
        
        system.debug('Size of Account List = ' + mapAcc.size());
        // Create SalesTargets for Testing  
            for(ID aID : ParentAccounts){
            aID = (string)aid;
        	system.debug('acct = '+ aID);
            if(MapAcc.containskey(aID)){
                Account thisAccount = MapAcc.get(aID);
               string thisname = thisAccount.name;
                if( thisname.substring(0, 18) == ('TestAcctWithTargets'))
            {
               Sales_Targets__c st1 = new Sales_Targets__c(Target_Name__c='MediaStar',Account__c =aID, Probability__c=10, value__c=1000.00,Year__c='2013');
               Sales_Targets__c st2 = new Sales_Targets__c(Target_Name__c='CME', Account__c = aID, Probability__c=20, value__c=100.00,Year__c='2013');
               Sales_Targets__c st3 = new Sales_Targets__c(Target_Name__c='Guide', Account__c = aID, Probability__c=10, value__c=1500.00,Year__c='2013');
               Sales_Targets__c st4 = new Sales_Targets__c(Target_Name__c='CMS', Account__c = aID, Probability__c=50, value__c = 2000.00, Year__c = '2013');
               Sales_Targets__c st5 = new Sales_Targets__c(Target_Name__c='PSIP', Account__c = aID,Probability__c=30, value__c = 2000.00, Year__c = '2013');
				system.debug('Finished populating the Targets for Account: '+ aID);
                system.debug(st1);
                system.debug(st2);
                system.debug(st3);
                system.debug(st4);
                system.debug(st5);
               system.debug('ready to add to TargetsToInsert');
               TargetsToInsert.add(st1);
               TargetsToInsert.add(st2);
               TargetsToInsert.add(st3);
               TargetsToInsert.add(st4);
               TargetsToInsert.add(st5);
                     
         }
  
            system.debug('Ready to insert all');
         try{
            database.insert(TargetsToInsert);
        }catch (DMLException e) {
            system.debug('Target Insert Failed with exception ' + e);
        }
       }
       }
      Database.SaveResult[] resultsTargets= Database.insert(TargetsToInsert, false);
            if(resultsTargets != null){
                for(Database.SaveResult result : resultsTargets){
                      if(result.isSuccess()){
                        system.debug(result.getId());
                    	newTargets.add(result.getId()); 
                      }else{
                          system.debug('target failed to insert');
                      }
                }
                
                string qry3 = 'Select id, account__c, account__r.name from Sales_Targets__c where account__r.id in :ParentAccounts';
                Map<ID, Sales_Targets__c> TargetsCheck =new Map<id, Sales_Targets__c>((List<Sales_Targets__c>)Database.query(qry3));
                for(id myid : TargetsCheck.keyset()){
                    if(TargetsCheck.get(myId).account__r.name.substring(0, 18) == 'TestAccountWithTargets') {
                        PageReference insertedPage = Page.SalesTargetInsert;
                     	insertedPage = ext.display();
                      system.assert(ext.numchildren > 0);
                        system.debug('numChildren = ' + ext.numChildren);
                    } else {
                        system.assert(ext.numchildren == 0);
                    }
                    PageReference myPage = new PageReference('/apex/SalesTargetInsert?id=:TargetsCheck.get(myID).account__r)');
                     
                }
            }
            for(ID AccountID : ParentAccounts){
                pageReference anAccount = new PageReference('/' + AccountID);
                system.debug('anAccount = ' + anAccount);
            }
                             
            
            
        }
        
    
    } 
}

 The Page:   Note:  The test coverage results show the entire display() method as uncovered code.

 

<apex:page standardController="Account" extensions="SalesTargetsController" action="{!display}">
    <style type="text/css">
        body {background: #F3F3EC; padding-top: 15px}
    </style>
    <apex:form >
        <apex:pageBlock id="pageBl" title="Sales Targets for the Year 2013" rendered="{!NOT(ISNULL(targets))}">
            <apex:pageBlockTable id="theTable" value="{!targets}" var="t" >
                
                <apex:column headerValue="Line" value="{!t.Name}" />
                <apex:column headerValue="Target Name" value="{!t.Target_Name__c}" />
                <apex:column value="{!t.Probability__c}"/>
                <apex:column value="{!t.Value__c}"/>
                <apex:column value="{!t.Contacted__c}"/>
                <apex:column value="{!t.No_Sale_Reason__c}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

 

The Controller

 

public class SalesTargetsController {
    private ApexPages.StandardController con {get;set;}
    private Account a;
    
    String myId = ApexPages.currentPage().getParameters().get('id');
    public integer numChildren = 0;
    public List<Sales_Targets__c> targets {get; set;}
    
    public SalesTargetsController(ApexPages.StandardController con){
        this.con = con;
        this.a =(Account)con.getRecord();
    }
    public PageReference display() {
    
        if(targets == null){
           targets = new List<Sales_Targets__c>();
        } else {
            targets.clear();
        }
 
        string qry = 'Select t.id, t.name, t.target_name__c, t.probability__c, t.value__c, t.Contacted__c, t.no_sale_reason__c from Sales_Targets__c t where Account__r.ID in :ParentAccounts Order by t.id';
     	targets=database.query(qry);
        system.debug('in display targets.size()=' + targets.size());
        if(targets.size() < 1 || targets == null){
            numChildren = 0;
            } else {
        numChildren = targets.size();
                system.debug('numChildres = ' + numChildren);
        }
        return null;
    }
    
}

 Thank you in advance for your help.

 

 

I am trying to write a Controller Extension for a custom object (Sales_Targets__c) that is parented by the Standard Account Object.  I am getting the error message above, but I don't understand what is causing it.  I can't see where I am assigning a Sales_Target to Account except where I am trying to assign the Account ID to the relationship field.  Here's the test code:

 

@isTest
private class TestSalesTargetsController {
    static  testMethod void TestSalesTargets() {
    
    Account myAcct = new Account();
        
    ApexPages.StandardController con = new ApexPages.Standardcontroller(myAcct);
    SalesTargetsController ext = new SalesTargetsController(con);
   
    Account testAcctWithTargets= new Account();
      Account testAcctWithNoTargets = new Account();
      Sales_Targets__c testTargetwithData = new Sales_Targets__c();
      Sales_Targets__c testTargetNoData= new Sales_Targets__c();
      List<Account> AcctsToInsert = new List<Account>();
      List<Sales_Targets__c> TargetsToInsert= new List<Sales_Targets__c>();
   
// create Accounts for Testing
    for(integer x = 0;x<25;x++){
        system.debug('Account = ' + testAcctWithTargets);
        testAcctWithTargets = new Account(Name='TestAcctWithTargets' + x);
        AcctsToInsert.add(testAcctWithTargets);
        testAcctWithNoTargets = new Account(Name='TestAcctWithNoTargets' + x);
        AcctsToInsert.add(testAcctWithNoTargets);
    }
        try{
            database.insert(AcctsToInsert);
        }catch (DMLException e) {
            system.debug('Account Insert Failed with exception ' + e);
        }
    
        // query Accounts for SalesTargets
        String accountQuery = 'select id from account where name contains TestAcct LIMIT 25';
        Map<id, Account> MapAcc = new Map<id, Account>((List<Account>)Database.query(accountQuery));
        
        system.debug('Size of Account List = ' + mapAcc.size());
        // Create SalesTargets for Testing  
        for (sObject a : MapAcc){
            a = (Account)a;
        	string aID = a.id;
        	system.debug('aID = '+ aID);
            if(a.name.contains('TestAcctWithTargets')){
               TestAcctWithTargets = new Sales_Targets__c(Target_Name__c='MediaStar',Account__c =aID,
               		Probability__c=10, value__c=1000.00,Year__c='2013');
               TargetsToInsert.add(TestAcctWithTargets);
               TestAcctWithTargets = new Sales_Targets__c(Target_Name__c='CME', Account__c = aID,
                     Probability__c=20, value__c=100.00,Year__c='2013');
               TargetsToInsert.add(TestAcctWithTargets);
               TestAcctWithTargets = new Sales_Targets__c(Target_Name__c='Guide', Account__c = aID,
                   Probability__c=10, value__c=1500.00,Year__c='2013');
               TargetsToInsert.add(TestAcctWithTargets);
               TestAcctWithTargets = new Sales_Targets__c(Target_Name__c='CMS', Account__c = aID,
                    Probability__c=50, value__c = 2000.00, Year__c = '2013');
               TargetsToInsert.add(TestAcctWithTargets);
				TestAcctWithTargets = new Sales_Targets__c(Target_Name__c='PSIP', Account__c = aID,
                    Probability__c=30, value__c = 2000.00, Year__c = '2013');
               TargetsToInsert.add(TestAcctWithTargets);
                     
         }
         try{
            database.insert(TargetsToInsert);
        }catch (DMLException e) {
            system.debug('Target Insert Failed with exception ' + e);
        }    
           
    }
}
}

 and here is the Controller extension:

 

public class SalesTargetsController {
    private ApexPages.StandardController con {get;set;}
    private Account a;
    public List<Sales_Targets__c> targets {get; set;}
    
    public SalesTargetsController(ApexPages.StandardController con){
        this.con = con;
        this.a =(Account)con.getRecord();
    }
    public PageReference display() {
        if(targets == null){
            targets = new List<Sales_Targets__c>();
        } else {
            targets.clear();
        }
 
        string qry = 'Select t.id, t.target_name_c, t.probability__c, t.value__c, t.Contacted__c, t.no_sale_reason__c from Sales_Targets__c t where AccountID = a.Id Order by t.id';
        targets=database.query(qry);
        return null;
    }
}

If someone can tell me what I'm doing wrong, I'd be eternally grateful.  The purpose is to create a page that can be inserted into the account detail section.

 

Thanks in advance,

 

I am writting a before insert trigger to copy information from the related Account record to an opporunity record on insert.  I'm creating the test account records, and using them in the opportunities that my test creates.  When I look at the Opportunities records as I am creating them, the Account fields  (name and ID) are filled in correctly on the opportunities.  When my trigger tries to build a set of accounts to copy from, the Account field(s) do not show up in the Trigger.new copies of the records, although all the other fields do show up.  I'll attach the trigger and the test code below.  Can someone help me understand what is happening to my Account fields?  Do I need to store the Account IDs in separate text fields to be able to get the accounts back?

 

Here's the code for the trigger:

 

trigger FillFieldsFromAcct on Opportunity (before insert){ 
{
    RecordType rt1 = [select id from RecordType where Name = 'PubDev Opportunities' and SobjectType = 'Opportunity' limit 1];
    Set<String> aNameSet1 = new Set<String>();
    List<Opportunity> oppsToInsert = new List<Opportunity>();
	List<Account> acctsToInsert = new List<Account>();
    Map<string,string> MasterMap= new Map<string,string>();
	
    for(Opportunity o : Trigger.New){
        o = (Opportunity)o;
        aNameSet1.add(o.Account.Name);
		MasterMap.put(o.name, o.account.name);
    }
    string qry = 'Select Name,Mobile__c, Video__c, Display__c, Monthly_Display_Imps__c, Monthly_Mobile_Imps__c, Monthly_Video_Imps__c,' + 
                    ' uniques__c, vertical__c, Pageviews__c  from Account where Name IN :aNameSet1';
     string qry2 = 'Select Name,Mobile__c, Video__c, Display__c, Monthly_Display_Impressions__c, Monthly_Mobile_Impressions__c, Monthly_Video_Impressions__c,' + 
                    ' uniques__c, vertical__c, Pageviews__c, Account.id, Account.name  from Opportunity where Account.name IN :aNameSet1';
                                          
    Map<string, Account>aNameToAccountMap = new Map<Id,Account>((List<Account>)Database.query(qry));
    Map<string, Opportunity>OppMap= new Map<string, Opportunity>((List<Opportunity>)Database.query(qry2));
    
    For(Opportunity thisopp : Trigger.new){
        thisopp = (Opportunity)thisopp;
        Account acctToCopy = new Account();
    
        if(thisopp.RecordTypeId != rt1.id){
            system.debug('thisopp.RecordTypeId = ' + thisopp.RecordTypeID );
            return;
        }
            string myAcct = thisopp.Account.name;
            acctToCopy = aNameToAccountMap.get(myAcct);
            if(acctToCopy == NULL){
                return;
            } 
            acctToCopy = (Account)acctToCopy;
        	system.debug('acctToCopy = '+ acctToCopy.name);
            thisopp.Display__c = acctToCopy.Display__c;
            thisopp.Mobile__c = acctToCopy.Mobile__c;
            thisopp.Video_PubDev__c = acctToCopy.Video__c;
            thisopp.Monthly_Display_Impressions__c = acctToCopy.Monthly_Display_Imps__c;
            thisopp.Monthly_Video_Impressions__c = acctToCopy.Monthly_Video_Imps__c;
            thisopp.Monthly_Mobile_Impressions__c = acctToCopy.Monthly_Mobile_Imps__c;
            thisopp.Uniques__c = acctToCopy.Uniques__c;
            thisopp.Pageviews__c = acctToCopy.Uniques__c;
            thisopp.Vertical__c = acctToCopy.Vertical__c;
        	system.debug('thisopp has been created -- back to Test ' + thisopp);
                    }
    
    }
}

 And here is the test:

 

@isTest
private class TestingOppTrigger {
static testMethod void verify_Opp_Fillin() {
List<Opportunity> oppsToInsert = new List<Opportunity>();
List<Account> acctsToInsert = new List<Account>();
RecordType rt = [select id from RecordType where Name = 'PubDev Opportunities' and SobjectType = 'Opportunity' limit 1];
integer y = 0;
Account s = new Account();

Opportunity o = new Opportunity();

//create Accounts

Account testAcct1 = new Account(Name='KBBTestAcct1', Vertical__c = 'Education',Uniques__c = 30000, Pageviews__c=20000,Display__c=TRUE, Video__c =TRUE,
Mobile__c = TRUE, Monthly_Display_Imps__c = 500000,Monthly_Mobile_Imps__c = 500003, Monthly_Video_Imps__c = 500002);
acctsToInsert.add(TestAcct1);
Account testAcct2 = new Account(Name='KBBTestAcct2');
acctsToInsert.add(TestAcct2);
try{
database.insert(acctsToInsert);
} catch(DMLException e) {
system.debug('ERROR: ' + e);
}

//Map inserted Accounts
string qry3 = 'select name, id, display__c, mobile__c, video__c, Monthly_Display_Imps__c, Monthly_video_Imps__c,' +
' Monthly_Mobile_Imps__c, Uniques__c, Pageviews__c, Vertical__c ' +
' from Account where CreatedDate = TODAY';
Map<string, Account> AccountMap = new Map<string, Account>((List<account>)Database.query(qry3));


//Create new Opportunities
for(y=0;y<2;y++){
Opportunity TestOppFilled = new Opportunity(RecordTypeID = rt.id, Name='KBBTestOpp' + y, Account= (Account)testAcct1,
StageName = '3 - On Hold',Id_Surrogate__c = 'KBBTestOpp' + y,
CloseDate = date.parse('3/30/2033'), Pub_Dev_Rep__c = 'Jason');
oppsToInsert.add(TestOppFilled);

Opportunity TestOppEmpty = new Opportunity(RecordTypeID = rt.id, Name= 'KBBTestOpp' + 1000 + y,
Account = (Account)testAcct2, StageName = '3 - On Hold',Id_Surrogate__c = 'KBBTestOpp' + 1000 + y,
CloseDate = date.parse('3/30/2033'), Pub_Dev_Rep__c = 'Jason');
oppsToInsert.add(TestOppEmpty);
}
// Insert Opportunities
try{
system.debug ('trying to insert Opportunities');
database.insert(oppsToInsert);
} catch(DMLException e1) {
system.debug('ERROR: ' + e1);
}

Map<string,Account>oIdToAccountMap = new Map<string, Account>();

for(Sobject z : Trigger.new){
Opportunity Oppty = new Opportunity();
Oppty = (Opportunity)z;
oIdToAccountMap.put(Oppty.Name, AccountMap.get(Oppty.Account.name));

//verify opportunity copy of account data
system.assertEquals(Oppty.Vertical__c,Oppty.Account.Vertical__c );
system.assertEquals(Oppty.Uniques__c,Oppty.Account.Uniques__c );
system.assertEquals(Oppty.Pageviews__c,Oppty.Account.Pageviews__c );
system.assertEquals(Oppty.Display__c,Oppty.Account.Display__c );
system.assertEquals(Oppty.Video_PubDev__c,Oppty.Account.Video__c );
system.assertEquals(Oppty.Mobile__c,Oppty.Account.Mobile__c );
system.assertEquals(Oppty.Monthly_Display_Impressions__c,Oppty.Account.Monthly_Display_Imps__c );
system.assertEquals(Oppty.Monthly_Video_Impressions__c,Oppty.Account.Monthly_Video_Imps__c);
system.assertEquals(Oppty.Monthly_Mobile_Impressions__c,Oppty.Account.Monthly_Mobile_Imps__c );
}
}
}

 

Thanks in advance.  This is my first non-trivial trigger, so I'm a newbie and will appreciate any insight you can offer.

 

kbb

I'm working on a trigger that copies some fields from an Account record into the related Opportunity record.  Here's the trigger code:

 

trigger FillFieldsFromAcct on Opportunity (before insert) 
{
    List<Account> myAccts = new List<Account>();
    RecordType rt = [select id from RecordType where Name = 'PubDev Opportunities' and SobjectType = 'Opportunity' limit 1];
    Account acctToCopy = new Account();
    For(Opportunity oppty : Trigger.New)
    {
        oppty = (Opportunity)Oppty;
       	if(oppty != NULL ) {
            if(oppty.RecordTypeId == rt.id){
                string myAcct = oppty.AccountId;
                string qry = 'select id, name, Display__c, Mobile__c, Video__c, Monthly_Display_Imps__c, Monthly_Mobile_Imps__c, Monthly_Video_Imps__c,' + 
                	'uniques__c, vertical__c, Pageviews__c  from Account where id = :myAcct limit 1';
                acctToCopy = database.query(qry);
				if(acctToCopy != null)
                acctToCopy = (Account)acctToCopy;
                oppty.Display__c = acctToCopy.Display__c;
               	oppty.Mobile__c = acctToCopy.Mobile__c;
               	oppty.Video_PubDev__c = acctToCopy.Video__c;
               	oppty.Monthly_Display_Impressions__c = acctToCopy.Monthly_Display_Imps__c;
                oppty.Monthly_Video_Impressions__c = acctToCopy.Monthly_Video_Imps__c;
               	oppty.Monthly_Mobile_Impressions__c = acctToCopy.Monthly_Mobile_Imps__c;
               	oppty.Uniques__c = acctToCopy.Uniques__c;
                oppty.Pageviews__c = acctToCopy.Uniques__c;
                oppty.Vertical__c = acctToCopy.Vertical__c;
            }
    	}
    }
}

 

This works as expected, but I need to get the coverage on my Test Class higher than 47%.  Here is the Test Class:

 

@isTest
private class TestOppTrigger {
static testMethod void verify_Acct_update() {
    List<Opportunity> oppsToInsert = new List<Opportunity>();
    List<Account> acctsToInsert = new List<Account>();
    RecordType rt = [select id from RecordType where Name = 'PubDev Opportunities' and SobjectType = 'Opportunity' limit 1];
    integer y = 0;
    string myString = 'test';
    Account testAcct1 = new Account(Name='TestAcct1', Vertical__c = 'Education',Uniques__c = 30000, 

Pageviews__c=20000,Display__c=TRUE, Video__c =TRUE,
    Mobile__c = TRUE, Monthly_Display_Imps__c = 500000,Monthly_Mobile_Imps__c = 500003, Monthly_Video_Imps__c = 500002, 
                                   UGC_Provider__c = myString);
    acctsToInsert.add(TestAcct1);
    Account testAcct2 = new Account(Name='TestAcct2', UGC_Provider__c = myString);
    acctsToInsert.add(TestAcct2);
    try{
    database.insert(acctsToInsert);
    } catch(DMLException e) {
        system.debug('ERROR:  ' + e);
    }
    
        Account testAcct = new Account();
        
        string qry = 'Select id, name from Account where UGC_Provider__c = :myString';
        List<Account> testAccounts = database.query(qry);
        
                for(y=0;y<30;y++){
                    if(math.mod(y,2)== 0) {
                    Opportunity TestOppFilled = new Opportunity(RecordTypeID = rt.id, Name='TestOpp' + x, Account = (Account)
                        testAcct1,  testString__c = myString, StageName = '3 - On Hold',
                        CloseDate = date.parse('3/30/2033'), Pub_Dev_Rep__c = 'Jason');
                    oppsToInsert.add(TestOppFilled);
                    
                    } else {
                    Opportunity TestOppEmpty = new Opportunity(RecordTypeID = rt.id, Name= 'TestOpp' + 1000 + x, 
                        testString__c =myString, Account = (Account)testAcct2, StageName = '3 - On Hold',
                        CloseDate = date.parse('3/30/2033'), Pub_Dev_Rep__c = 'Jason');
                    oppsToInsert.add(TestOppEmpty);
                    }
                    system.debug('Size of list = ' + oppsToInsert.size() + ' at bottom of loop');
                }
                system.debug ('just before try-catch');
                try{
                    system.debug ('trying to insert Opportunities');
                    database.insert(oppsToInsert);
                } catch(DMLException e1) {
                    system.debug('ERROR:  ' + e1);
                    }
            
        string qry1 = 'Select Account.id, Name, Vertical__c,Uniques__c, Pageviews__c,Display__c, Video_PubDev__c, ' +
            'Mobile__c, Monthly_Display_Impressions__c,Monthly_Mobile_Impressions__c, Monthly_Video_Impressions__c from Opportunity ' + 
            'where testString__c = :myString limit 100';
    
        List<Opportunity> Results = new List<Opportunity>();
        Results = database.query(qry1);
       
		for (Opportunity Oppty : Results){
            if (Oppty != NULL) {
            	Oppty = (Opportunity)Oppty; 
            }
        system.assertEquals(Oppty.Vertical__c,Oppty.Account.Vertical__c );
        system.assertEquals(Oppty.Uniques__c,Oppty.Account.Uniques__c );
		system.assertEquals(Oppty.Pageviews__c,Oppty.Account.Pageviews__c );
        system.assertEquals(Oppty.Display__c,Oppty.Account.Display__c );
        system.assertEquals(Oppty.Video_PubDev__c,Oppty.Account.Video__c );
        system.assertEquals(Oppty.Mobile__c,Oppty.Account.Mobile__c );      
        system.assertEquals(Oppty.Monthly_Display_Impressions__c,Oppty.Account.Monthly_Display_Imps__c );
        system.assertEquals(Oppty.Monthly_Video_Impressions__c,Oppty.Account.Monthly_Video_Imps__c);
        system.assertEquals(Oppty.Monthly_Mobile_Impressions__c,Oppty.Account.Monthly_Mobile_Imps__c ); 
             
     
        }
        
      }
    }

 From the display of code coverage, it looks like I am doing something wrong that is causing the system to believe that the actual copying is not being tested.  Is there a better way to test this than system.assertEquals?  Any help from a more experienced developer would be most welcome.

 

I'm attempting to write a trigger on an opportunity that brings over information from the related Account and adds it to the Opportunity just inserted.  This is my first attempt at writing a trigger.  For some reason my soql queries are not returning any rows.  I will post my code for the trigger and the test I'm trying to create below.  Can someone spot what I'm doing wrong and tell me how to correct it?  Thanks very much in advance.

 

The Trigger:

trigger FillFieldsFromAcct on Opportunity (before insert) {
    string holdAccountId = ' ';
    Account acct = new Account();
    Account acctToCopy= new Account();
    Opportunity opp = new Opportunity();
    for(Opportunity a : Trigger.New){
    opp = (Opportunity)Trigger.New[0];
    holdAccountId = a.Account.id;
    }
    system.debug(holdAccountId);
    acct=[SELECT id, Display__c, Mobile__c, Video__c, Monthly_Display_Imps__c, Monthly_Mobile_Imps__c, Monthly_Video_Imps__c, Uniques__c, Vertical__c from Account where id = :holdAccountId limit 1];
    acctToCopy = (Account)acct;
    opp.Display__c = acctToCopy.Display__c;
    opp.Mobile__c = acctToCopy.Mobile__c;
    opp.Video__c = acctToCopy.Video__c;
    opp.Monthly_Display_Impressions__c = acctToCopy.Monthly_Display_Imps__c;
    opp.Monthly_Video_Impressions__c = acctToCopy.Monthly_Video_Imps__c;
    opp.Monthly_Mobile_Impressions__c = acctToCopy.Monthly_Mobile_Imps__c;
    opp.Uniques__c = acctToCopy.Uniques__c;
    opp.Vertical__c = acctToCopy.Vertical__c;
    system.debug(opp);
}

 And here is the test:

@isTest
private class TestOppTrigger {
static testMethod void verify_Acct_update() {
	integer x = 0;
	Account testAcct1 = new Account(Name='TestAcct1', Vertical__c = 'Education',Uniques__c = 30000, Pageviews__c=20000,Display__c=TRUE, Video__c =TRUE,
	Mobile__c = TRUE, Monthly_Display_Imps__c = 500000,Monthly_Mobile_Imps__c = 500003, Monthly_Video_Imps__c = 500002);
	database.insert(testAcct1);
    string myAccount=testAcct1.id;
	Opportunity TestOp1 = new Opportunity(Name='TestOp1', StageName = '3 - On Hold',CloseDate = date.parse('3/30/2033'), Pub_Dev_Rep__c ='Tara');
	database.insert(TestOp1);
	string qry = 'select id, Name, Vertical__c,Uniques__c, Pageviews__c,Display__c, Video_PubDev__c, Mobile__c, Monthly_Display_Imps__c,Monthly_Mobile_Imps__c, Monthly_Video_Imps__c from Opportunity where id = :myAccount limit 1 ';
	List<Opportunity> Results = new List<Opportunity>();
	Results = database.query(qry);
    system.debug(Results);
	Results[0] = (Opportunity)Results[0];
		if(Results[x].Name == 'TestOp1'){
			system.assertEquals(TestOp1.Vertical__c,TestAcct1.Vertical__c );
			system.assertEquals(TestOp1.Uniques__c,TestAcct1.Uniques__c );
			system.assertEquals(TestOp1.Pageviews__c,TestAcct1.Pageviews__c );
			system.assertEquals(TestOp1.Display__c,TestAcct1.Display__c );
			system.assertEquals(TestOp1.Video_PubDev__c,TestAcct1.Video__c );
			system.assertEquals(TestOp1.Mobile__c,TestAcct1.Mobile__c );
			system.assertEquals(TestOp1.Monthly_Display_Impressions__c,TestAcct1.Monthly_Display_Imps__c );
			system.assertEquals(TestOp1.Monthly_Video_Impressions__c,TestAcct1.Monthly_Video_Imps__c);
			system.assertEquals(TestOp1.Monthly_Mobile_Impressions__c,TestAcct1.Monthly_Mobile_Imps__c );
		}else{
            system.debug('One of the assertions failed');
		
		
		}
	}
}

 Thank you so much in advance

 

I'm having a problem getting a pageBlockTable to display a list of Accounts with checkboxes.  It can't seem to find the List I'm asking it to display -- all that shows up is the header row and a blank table.

 

Here is the page code:

<apex:page standardController="Titan_Contract_Orders_Generator__c" extensions="TitanConOrdExtension" >
<apex:sectionHeader title="{!$ObjectType.Titan_Contract_Orders_Generator__c.label} Edit" subtitle="New {!$ObjectType.Titan_Contract_Orders_Generator__c.name}"/>
<apex:form >
<apex:pageBlock title="{!$ObjectType.Titan_Contract_Orders_Generator__c.label} Edit" mode="edit" tabStyle="Titan_Contract_Orders_Generator__c">
<apex:pageBlockButtons >
<apex:commandButton action="{!save}" value="Save"/>
<apex:commandButton action="{!cancel}" value="Cancel"/>
</apex:pageBlockButtons>
<apex:pageBlockSection showHeader="true" title="Basic Information" columns="2" >
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Number_of_Stations_In_Contract__c}"/>
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Renewal_or_Extension__c}"/>
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Who_to_Bill__c}"/>
<apex:inputField required="true" value="{!Titan_Contract_Orders_Generator__c.Account__c}"/>
<apex:inputField required="true" value="{!Titan_Contract_Orders_Generator__c.Contract_Start_Date__c}"/>
<apex:inputField required="true" value="{!Titan_Contract_Orders_Generator__c.Contract_End_Date__c}"/>
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Contract_for__c}"/>
<apex:inputField required="true" value="{!Titan_Contract_Orders_Generator__c.Date_Submitted__c}"/>
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Status__c}"/>
<apex:inputField required="true" value="{!Titan_Contract_Orders_Generator__c.Duration_in_Months__c}"/>
<apex:pageBlockSectionItem />
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Date_to_be_Billed__c}"/>
<apex:pageBlockSectionItem />
</apex:pageBlockSection>
<apex:pageBlockSection title="Input Contacts">
<apex:inputField required="true" value="{!Titan_Contract_Orders_Generator__c.Customer_Contact__c}"/>
<apex:inputField required="true" value="{!Titan_Contract_Orders_Generator__c.Billing_Contact__c}"/>
</apex:pageBlockSection>

<apex:pageBlockSection showHeader="true" title="Notes and Comments">
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Comments_Internal_Use_Only__c}"/>
<apex:outputField value="{!Titan_Contract_Orders_Generator__c.Description__c}"/>
</apex:pageBlockSection>
<apex:pageBlockSection showHeader="true" title="Template Information for Orders" columns="2">
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Product__c}"/>
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Price_First_Year__c}"/>
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Orders_Generated__c}"/>
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Price_Second_Year__c}"/>
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Invoice_From__c}"/>
<apex:inputField value="{!Titan_Contract_Orders_Generator__c.Price_Third_Year__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock tabStyle="Titan_Contract_Orders_Generator__c" >
<apex:pageBlockButtons location="top">
<apex:commandButton action="{!showAccounts}" value="Show Accounts" />
<apex:commandButton action="{!processSelectAccts}" value="Process Selected"/>
<apex:commandButton action="{!removeSelected}" value="Remove Selected"/>
<apex:commandButton action="{!selectAll}" value="Select All"/>
<apex:commandButton action="{!deselectAll}" value="Unselect All"/>
<apex:commandButton action="{!cancel}" value="Cancel"/>
</apex:pageBlockButtons>

<apex:pageBlockSection id="ChildAccounts" showHeader="true" title="Select the Accounts involved in this contract" columns="2">
<apex:pageBlockTable width="30%" columns="2" value="{!chooseAccts}" var="acc">
<apex:column width="10%" headerValue="Select">
<apex:inputCheckbox value="{!acc.selected}" />
</apex:column>
<apex:column headerValue="Name" value="{!acc.acct.Name}"/>
</apex:pageBlockTable>
</apex:pageBlockSection>

</apex:pageBlock>
</apex:form>
</apex:page>

 

Here is the controller for my custom object:

public with sharing class TitanConOrdExtension {
private final Titan_Contract_Orders_Generator__c ext;

public TitanConOrdExtension(ApexPages.StandardController con) {
this.ext = (Titan_Contract_Orders_Generator__c)con.getRecord();
}

public List<tempAcct> childAccounts {get; set;}
public List<tempAcct> chooseAccts {get; set;}
public List<tempAcct> selectedAccts{get;set;}
public List<tempOrder> chooseOrders {get;set;}


public PageReference initAcctList() {
List<Account> childAccounts = new List<Account>();
List<tempAcct> chooseAccts= new List<tempAcct>();

if('{!Contract_for__c}' == 'A Single Station'){
string singleAccount = '{!Titan_Contract_Orders_Generator__c.Account__c}';
string sqry = 'SELECT id, Name FROM Account WHERE id = :singleAccount LIMIT 1';
childAccounts = Database.query(sqry);
chooseAccts.add(new tempAcct(childAccounts[0]));
system.debug('Single Account --- ' + childAccounts[0]);
system.debug('Adding '+ singleAccount + 'to chooseAccts.');
} else {
childAccounts = new List<Account>();
string parentvar = this.ext.Account__c;
string mqry='SELECT id, Name FROM Account WHERE parent.id = :parentVar ORDER BY Name asc LIMIT 200';
childAccounts = Database.query(mqry);
system.debug('childAccounts -- ' + childAccounts.size());
for(Account myAcct : childAccounts){
chooseAccts.add(new tempAcct(myAcct));
system.debug('Adding '+ myAcct + 'to chooseAccts.');
system.debug('ready to exit initAcctList now.');
}
}
return null;
}

public List<tempAcct> showAccounts() {
system.debug('Starting getAccounts');
if(chooseAccts == NULL){
initAcctList();
}
return chooseAccts;
}

}

 

I've left off the other action methods for brevity's sake.

 

Can someone tell me the correct way to reference the chooseAccts List so that the table can find it?  I've tried every way I can think of.  The heap dump shows that the chooseAccts List is being properly populated.

 

Thanks in advance for any help.  This is driving me crazy.  (I'm a relative newby, as you can probably tell).

 

The error is: Failed to create createContainerMember for containerId=1dc5000000000lrAAA: This container member belongs to a container that currently has an unfinished save request with deploymentId=1drR00000001PF8. You may not modify any members in this container until it completes.: Metadata Container ID

I have waited for over 24 hours and it still comes up every time I try to save my Apex code.  What can I do to clear it out so I can save code again?  What does this mean or how can I avoid it  in the future.  

Thanks so much for any insight.  This has me dead in the road currently.

kathybb
  • September 21, 2014
  • Like
  • 1
I've run into a problem with my Test code for a Controller extension.  The error message I get is: Constructor not defined: [Test_Line_Edit_Extension].&lt;Constructor&gt;(ApexPages.StandardController).  I need to get this fixed so I can deploy it to production to enable me to get rid of code that somehow made it into Production without accompanying test code.  Here is my test code:
@istest
public class Test_Line_Edit_Extension 
{
	public static testmethod void Test_Line_Edit_Extension()
	{
        Order_Line_Item__c initLI = new Order_Line_Item__c();
        ApexPages.StandardController sc = new ApexPages.standardController(initLI);
        Test_Line_Edit_Extension ext1 = new Test_Line_Edit_Extension(sc);
        ext1.getRecord(initLI);
        
       	Product2 myProduct = [select id, ProductCode, Family, Description
    	from Product2 where productCode = 'K PSIP MSL' Limit 1];
		Order__c myOrder = new Order__c();
		List<Order__c>OrdersList = new List<Order__c>();
		List<Order_Line_Item__c> LIList = new List<Order_Line_Item__c>();
		Account testAccount = new Account(Name = 'KBB Test Account');
		insert testAccount;
        if(testAccount.id != null)
        {
			myOrder = new Order__c(Customer_Account__c = testAccount.id);
		
			for(integer x = 1; x< 10;x++)
			{
			Order_Line_Item__c myLineItem = new Order_Line_Item__c(Name = myProduct.productCode + x, Price_per_unit__c = x,
            Quantity__c = 3, Year_of_Contract__c = 2,Type_of_Sale__c = 'Renewal',Order_Number__c = myOrder.id);
			system.assertEquals(myProduct.name, 'K PSIP MSL');
			system.assertEquals(myProduct.productCode, myLineItem.Product__c);
            }
        }
    }
	

}

Here is the code I'm trying to test:
public with sharing class LineEditExtension {

    private final Order_Line_Item__c m_ext {get;set;}
    public Order_Line_Item__c currentLine {get;set;}
    public ApexPages.StandardController m_con {get;set;}
    public ApexPages.StandardController m_Gstd {get;set;}
    public string m_currentLineId {get;set;}    
   
    public LineEditExtension(ApexPages.StandardController stdController){ 
        m_ext = (Order_Line_Item__c)stdController.getRecord();
    }
    
    public PageReference SaveAndNew(){
        ApexPages.StandardController m_Gstd = new ApexPages.StandardController(m_ext);
        PageReference OrderPage = m_Gstd.save(); 
        m_currentLineId=m_Gstd.getId(); 
        PageReference returnPage = new PageReference('/a07/e');
        return returnPage;
    }                                          
}

And here's the page:
<apex:page standardController="Order_Line_Item__c" extensions="LineEditExtension">
    <apex:sectionHeader title="{!$ObjectType.Order_Line_Item__c.label} Edit" subtitle="{!Order_Line_Item__c.name}"/>
    <apex:form >
    <apex:pageBlock title="{!$ObjectType.Order_Line_Item__c.label} Edit" mode="edit">
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save"/>
            <apex:commandButton action="{!saveAndNew}" value="Save & New"/>
            <apex:commandButton action="{!cancel}" value="Cancel"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection showHeader="true" title="Information" columns="2">
            <apex:inputField required="true" value="{!Order_Line_Item__c.Product__c}"/>
            <apex:pageBlockSectionItem />
            <apex:pageBlockSectionItem />
            <apex:pageBlockSectionItem />
            <apex:inputField required="true" value="{!Order_Line_Item__c.Order_Number__c}"/>
            <apex:inputField value="{!Order_Line_Item__c.Length_of_Subscription__c}"/>
            <apex:pageBlockSectionItem />
            <apex:inputField value="{!Order_Line_Item__c.Year_of_Contract__c}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection showHeader="true" title="Details" columns="2">
            <apex:inputField value="{!Order_Line_Item__c.Quantity__c}"/>
            <apex:inputField value="{!Order_Line_Item__c.Type_of_Sale__c}"/>
            <apex:inputField value="{!Order_Line_Item__c.Price_per_Unit__c}"/>
            <apex:inputField value="{!Order_Line_Item__c.New_Money__c}"/>
            <apex:inputField value="{!Order_Line_Item__c.Renewal_Increase_money__c}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection showHeader="true" title="System Information" columns="2">
            <apex:pageBlockSectionItem />
            <apex:pageBlockSectionItem />
            <apex:inputField required="true" value="{!Order_Line_Item__c.Name}"/>
            <apex:pageBlockSectionItem />
        </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Any insight will save my sanity.
Thanks,
KathyBB
  • September 25, 2014
  • Like
  • 0

The system is throwing this error:FATAL_ERROR System.QueryException: IN operator must be used with an iterable expression.

 

The Query string is: 

string findTestPOs = 'SELECT id, name,Finalized__c,PO_Notes__c,Status__c, Ship_to_location__c, Expedite__c, PO_Date__c, Total_Price__c,Category__c,SFDC_Purchase_Order__c.ownerID FROM SFDC_Purchase_Order__c WHERE id in :MyPOIdSet';
The lines throwing the error are:
List<SFDC_Purchase_Order__c>myNewPOs = new List<SFDC_Purchase_Order__c>();
myNewPOs = database.query(FindTestPOs);

 

I have 2 questions:

What can I do to fix this error?

How can a Set not be iterable?

 

This reallly has me puzzled.  This is keeping my Test  code from running to completion.

I really appreciate any insight anyone has. 

 

Thank you very much.

Kathybb

I have a requirement to render a visualforce page in PDF and attach it to the relevant Purchase Order (custom Object).  Here is my visualforce code:

<apex:page standardController="SFDC_Purchase_Order__c" renderas="PDF" extensions="AttachPRTOPOExtension" sidebar="false" showHeader="false" name="PDFPO">
    <br />
    <br />
    <center><big><big><br /> Broadcast Interactive Media</big></big></center><br/>
    <apex:outputPanel id="POInfo" layout="Block" style="font:Arial font-size: 9pt">
    <apex:outputtext value="Purchase Order Number:  " />
        <apex:outputField value="{!SFDC_Purchase_Order__c.Name}"/>
        <br />
        <apex:outputtext value="Date:  " />
        <apex:outputField value="{!SFDC_Purchase_Order__c.PO_Date__c}"/><br/>
        <apex:outputtext value="Purchase Order Status:  " />
        <apex:outputField value="{!SFDC_Purchase_Order__c.Status__c}"/><br/>
        <br />
        <apex:outputtext value="Deliver To:  " />
        <apex:outputField value="{!SFDC_Purchase_Order__c.Ship_To_Location__c}"/>
        
        <br />
        <br />
    </apex:outputPanel>
      
    <apex:dataTable value="{!m_displayResultList}" var="r" border="1px" cellpadding="2px" cellspacing="2px" width="100%" style="font:Arial fontsize=7pt">
        <apex:column width="10%" headerValue="Req #" value="{!r.name}" />
        <apex:column width="10%" headerValue="Requested For" value="{!r.createdby.name}"/>
        <apex:column width="10%" headerValue="Date" value="{!r.Request_Date__c}"/>
        <apex:column width="10%" headerValue="Quantity" value="{!r.Quantity__c}" />
        <apex:column width="10%" headerValue="Item Requested" value="{!r.item_Requested__r.name}" />
        <apex:column width="10%" headerValue="Price" value="{!r.item_requested__r.Price_per_unit__c}" />
        <apex:column width="10%" headerValue="Ext. Price" value="{!r.Extended_Price__c}" />
        <apex:column width="10%" headerValue="Needed by" value="{!r.Receive_by_Date__c}" />
    </apex:dataTable>
    
    
</apex:page>

 And here are the relevant method from my controller extension:

public PageReference ViewPDF()
    {   
        system.debug('*************************START VIEWPDF******************************');
        system.debug('m_currentId = '+m_currentId);
        List<SFDC_Purchase_Requisition__c> m_reqResultList = new List<SFDC_Purchase_Requisition__c>();
        List<SFDC_Purchase_Requisition__c> m_displayResultList = new List<SFDC_Purchase_Requisition__c>();
        PageReference retPDF = new PageReference('/apex/PDFPO?id='+m_currentId);
        system.debug('m_myPO = '+ m_myPO);
        string PDFqueryPO = 'select Name, CreatedBy.name, Ship_To_Location__c,Expedite__c,PO_Date__c, Owner.id, Total_Price__c, PO_Notes__c from SFDC_Purchase_Order__c where Id = :m_currentId Limit 1';
        
        SFDC_Purchase_Order__c PDFPO = new SFDC_Purchase_Order__c();
        PDFPO =(SFDC_Purchase_Order__c)database.query(PDFqueryPO);
        string PDFReqResultListquery = m_RequestQueryByPOid;
        m_reqResultList= database.query(PDFReqResultListquery);
        for(SFDC_Purchase_Requisition__c thisReq : m_reqResultList){
            system.debug('thisReq.name = '+ thisReq.name);
            system.debug('thisReq.createdby.name = '+ thisReq.createdby.name);
                        system.debug('thisReq.Request_Date__c) = '+ thisReq.Request_Date__c);
                        system.debug('thisReq.quantity__c = '+ thisReq.quantity__c);
                        system.debug('thisReq.item_requested__r.name = '+ thisReq.item_requested__r.name);
                        system.debug('thisReq.item_requested__r.price_per_unit__c = '+ thisReq.item_requested__r.price_per_unit__c);
            system.debug('thisReq.extended_price__c = '+ thisReq.extended_price__c);
            system.debug('thisReq.receive_by_date__c = '+ thisReq.receive_by_date__c);
        m_displayResultList = new List<SFDC_Purchase_Requisition__c>();
        For(SFDC_Purchase_Requisition__c x : m_reqResultList)
        {
            if(x != null){
            x = (SFDC_Purchase_Requisition__c)x;
            m_displayResultList.add(x);
            system.debug('x='+x);
            system.debug(m_displayResultList.size());
            }
        }
        }
        m_PDFPage = attach();
        system.debug('about to return m_PDFPage from ViewPDF = '+ m_PDFPage);
        return m_PDFPage;
    }
      
    public PageReference attach() 
    {
        system.debug('********************************START ATTACH**********************');
         system.debug('m_currentId = '+m_currentId);
        Attachment myAttach = new Attachment();
         system.debug('m_currentId = '+m_currentId);
        myAttach.ParentId = m_currentId;    //Id of the object to which the page is attached
        if(m_myPO != null)
        {
            string myFileName = (m_myPO.name + ' - '+ date.TODAY() + '.PDF');
            myAttach.name = myFileName;
            myAttach.description = 'BIM Purchase Order Summary for '+ m_myPO.name +' Created on '+ date.Today() +' by '+ m_myPO.CreatedBy.name;
            PageReference myPdf = new PageReference('/apex/PDFPO?id=' + m_currentID);
                myAttach.body = myPdf.getContentAsPdf();
            try 
            {
                database.SaveResult sra = database.insert(myAttach);
                if(sra.issuccess() == true)
                {
                m_currentAttachId = sra.getID();
                }
                else
                {
                    // Operation failed, so get all errors                
                    for(Database.Error err : sra.getErrors()) 
                    {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Attachment fields that affected this error: ' + err.getFields());
                    } 
                } 
            } catch(Exception e){
                system.debug('Creation of PDF Failed');
                system.debug('Message was: '+ e);
        }
    }
        system.debug('about to return m_PDFPage from attach = '+ m_PDFPage);
        return m_PDFPage;
    }

 The debug statements confirm that the list is populated correctly, but when the page renders, it displays properly down to the header row on the table and is blank for the rest of the table.  I would be very grateful if someone could point out what I am doing wrong.  The attach method works perfectly, but the table data is missing every time.

 

Thanks in advance for any insight.

 

kathybb

I'm writing a method to create a PDF Purchase Order and add it as an attachment to the PO record (custom object).

Here's the relavent apex code:

 

 public PageReference ViewPDF()
    {      
        system.debug('m_currentId = '+m_currentId);
        List<SFDC_Purchase_Requisition__c> m_reqResultList = new List<SFDC_Purchase_Requisition__c>();
        PageReference retPDF = new PageReference('/apex/PDFPO?id='+m_currentId);
        system.debug('m_myPO = '+ m_myPO);
        string PDFqueryPO = 'select Name, CreatedBy.name, Ship_To_Location__c,Expedite__c,PO_Date__c, Owner.id, Total_Price__c, PO_Notes__c from SFDC_Purchase_Order__c where Id = :m_currentId Limit 1';
        
        SFDC_Purchase_Order__c PDFPO = new SFDC_Purchase_Order__c();
        PDFPO =(SFDC_Purchase_Order__c)database.query(PDFqueryPO);
        string PDFReqResultListquery = m_RequestQueryByPOid;
        m_reqResultList= database.query(PDFReqResultListquery);
        m_displayResultList = new List<SFDC_Purchase_Requisition__c>();
        For(SFDC_Purchase_Requisition__c x : m_reqResultList)
        {
            if(x != null){
            x = (SFDC_Purchase_Requisition__c)x;
            m_displayResultList.add(x);
            }
           m_PDFPage = attach();
        }
        return m_PDFPage;
    }
      
    public PageReference attach() 
    {
         system.debug('m_currentId = '+m_currentId);
        Attachment myAttach = new Attachment();
         system.debug('m_currentId = '+m_currentId);
        myAttach.ParentId = m_currentId;    //Id of the object to which the page is attached
        if(m_myPO != null)
        {
            string myFileName = (m_myPO.name + ' - '+ date.TODAY() + '.PDF');
            myAttach.name = myFileName;
            PageReference myPdf = new PageReference('/apex/PDFPO?id=' + m_currentID);
            
            
            myAttach.body = myPdf.getContentAsPdf();
            try 
            {
                database.SaveResult sra = database.insert(myAttach);
                if(sra.issuccess() == true)
                {
                m_currentAttachId = sra.getID();
                }
                else
                {
                    // Operation failed, so get all errors                
                    for(Database.Error err : sra.getErrors()) 
                    {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Attachment fields that affected this error: ' + err.getFields());
                    } 
                } 
            } catch(Exception e){
                system.debug('Creation of PDF Failed');
                system.debug('Message was: '+ e);
        }
    }
        return m_PDFPage;
    }

 And here's the visualforce page 

 

<apex:page standardController="SFDC_Purchase_Order__c" extensions="AttachPRTOPOExtension" name="PDFPO" renderAs="PDF" action="{!ViewPDF}">
	<apex:outputPanel id="POInfo" layout="Block" style="font:Arial font-size: 9pt">
		<apex:outputField value="{!SFDC_Purchase_Order__c.Name}"/>
		<br />
		<apex:outputField value="{!SFDC_Purchase_Order__c.PO_Date__c}"/>
		<apex:outputField value="{!SFDC_Purchase_Order__c.Status__c}"/>
		<br />
		<apex:outputField value="{!SFDC_Purchase_Order__c.Ship_To_Location__c}"/>
		<apex:outputField value="{!SFDC_Purchase_Order__c.Expedite__c}"/>
		<br />
        <br />
	</apex:outputPanel>     
	<apex:DataTable value="{!m_displayResultList}" var="r" border="1px" cellpadding="1px" cellspacing="2px">
		<apex:column width="10%" headerValue="Request" value="{!r.name}" />
		<apex:column width="10%" headerValue="Requested By" value="{!r.Createdby.name}"/>
		<apex:column width="10%" headerValue="Request Date" value="{!r.CreatedDate}"/>
		<apex:column width="10%" headerValue="Quantity" value="{!r.Quantity__c}" />
		<apex:column width="10%" headerValue="Item Requested" value="{!r.Item_Requested__r.Name}" />
		<apex:column width="10%" headerValue="Price" value="{!r.Item_Requested__r.Price_per_unit__c}" />
		<apex:column width="10%" headerValue="Extended Price" value="{!r.Extended_Price__c}" />
		<apex:column width="10%" headerValue="Receive-by Date" value="{!r.Receive_by_Date__c}" />
	</apex:DataTable>
	<apex:relatedList list="Purchase_Requisitions__r" Title="Requisitions connected with this PO"/>
     <apex:relatedList list="NotesandAttachments" Title="Notes and Attched PDF PO"/>
</apex:page>

 I'm compiling it as version 25, to avoid the bug earlier reported to Salesforce.  

 

Can someone explain what I'm doing wrong in my controller extension?  This is the first time I've tried to generate a PDF file and attach it to a record, so any insight would be very appreciated.

Thanks in advance.

 

I'm trying to write a test class, but I keep getting this error message.  Here's my code:

@isTest
public class Test_AttachPRTOPOExtension_Final{
    static testmethod void Test_Attachment_process() {
        SFDC_Purchase_Order__c myOrder = new SFDC_Purchase_Order__c();
        List<SFDC_Purchase_Requisition__c> RequestsToUpdate = new List<SFDC_Purchase_Requisition__c>();
        List<SFDC_Purchase_Items__c> ItemsToUpdate = new List<SFDC_Purchase_Items__c>();
        //Instatiate Controllers
        
        ApexPages.StandardController con = new ApexPages.StandardController(myOrder);
        AttachPRTOPOExtension ext = new AttachPRTOPOExtension(con);
          
        // create items
        List<SFDC_Purchase_Items__c> newItems= new List<SFDC_Purchase_Items__c>();
        for(integer i=0;i<100;i++){
            SFDC_Purchase_Items__c thisitem = new SFDC_Purchase_Items__c(name ='item '+ i);
            newItems.add(thisItem);
        }	//end for
        if(newItems.size() != 100){
            system.debug('newItems <> 100'+ newItems.size());
                } else {		//end if
        system.assertEquals(newItems.size(),100);
                }		// end else
        try {
            Database.SaveResult[] sriList = database.insert(newItems);
            for (Database.SaveResult sri : sriList) {
    			if (sri.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted item. Item ID: ' + sri.getId());
    } else {
        // Operation failed, so get all errors                
        for(Database.Error err : sri.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Item fields that affected this error: ' + err.getFields());
        }		// end inner for
    }			// end else
}				// 3ne outer for
        } catch (DMLEXCEPTION e){
            system.debug('insertItems failed: ' + e);
                         }	//end catch
		List<SFDC_Purchase_Order__c> newOrders = new List<SFDC_Purchase_Order__c>();
        date newDate= date.today();
        ID myPurchaser = [select id from User where  has_purchasing_authority__c = true Limit 1] ;
        ID myApprover = [select id from User where (has_approval_authority__c = true) and (has_purchasing_authority__c = false) Limit 1] ;
        List<SFDC_Purchase_Requisition__c> newReqs= new List<SFDC_Purchase_Requisition__c>();
       
        for(integer i=0;i<100;i++){
            SFDC_Purchase_Requisition__c thisReq = new SFDC_Purchase_Requisition__c(status__c = 'Sent to Purchaser',Department__c = 'Dev CR',Quantity__c = i,
                Item_requested__c = newItems[i].id, Approver__c = myApprover, Purchaser__c = myPurchaser); 
            newReqs.add(thisReq);
        }
        if(newReqs.size() != 100){
            system.debug('newIReqs <> 100'+ newReqs.size());
                } else {
        system.assertEquals(newReqs.size(),100);
                }
        Set<string> ReqSet = new Set<string>();
           try {
            Database.SaveResult[] srrList = database.insert(newReqs);
            for (Database.SaveResult srr : srrList) {
    if (srr.isSuccess()) {
        ReqSet.add(srr.getId());
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted Requisition. Requisition ID: ' + srr.getId());
    } else {
        // Operation failed, so get all errors                
        for(Database.Error err1 : srr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Requisition fields that affected this error: ' + err.getFields());
        }		//end inner for
    }		//end else
}			// end  outer for
        } catch (DMLEXCEPTION e){
            system.debug('insertReqs failed: ' + e);
        }
         List<SFDC_Purchase_Requisition__c> AllReqs = new List<SFDC_Purchase_Requisition__c>(AttachPRTOPOExtension.m_requestQuery);               }

        // create Orders

        

    for(integer o=0;o < 20; o++){
            SFDC_Purchase_Order__c anOrder = new SFDC_Purchase_Order__c(PO_notes__c = 'note number '+ o, Ship_To_Location__c= 'Cedar Rapids Office',
                                                                        Category = 'Dev CR', Expedite= true,
                                                                        PO_Date__c = newDate);
            newOrders.add(anOrder);
        }
    Test.startTest();
    	Set<string> OrderSet = new Set<string>();
        integer placeInList = 0;
        for(myOrder : newOrders){
            OrderSet.add(myOrder.id);
            myOrder = (SFDC_PurchaseOrder__c)myOrder;
            holdPage = SavePO();
            if(holdPage.URLfor = AttachPRTOPOExtension.m_DetailPage.urlFor){
                AssertNotEquals(AttachPRTOPOExtension.m_currentID, null);}
                AssertNotEquals(AttachPRTOPOExtension.m_resultList.size(), 0);
                for(AttachPRTOPOExtension.tempPR myReq : AttachPRTOPOExtension.m_resultList){
                    myReq = (AttachPRTOPOExtension.tempPR)myReq;
                    for(x=PlaceInList : x<PlaceInList+5 :x++){
                        myReq.selected = true;
                    }
                    PlaceInList++; 
                    AttachPRTOPOExtension.processSelected();
                    AssertEquals(AttachPRTOPOExtension.m_resultList.size(),5);
                    holdPage=AttachPRTOPOExtension.FinalizePO();
                    AssertEquals(ApexPage.currentPage().getURL(),AttachPRTOPOExtension.m_DetailPageROURL + AttachPRTOPOExtension.m_currentId)
                        }  //end inner for
						
                }  //end outer for
            Test.stoptest();
    List<SFDC_Purchase_Order__c> checkPOs = new List<SFDC_Purchase_Order__c>([select id,name,PO_Notes__c,
                                                                    PO_Date__c,Category__c, numRequisitions__c,
                                                                    Total_Price__c, Status__c,Ship_To_Location__c,
                                                                    Expedite__c, Finalized__c from
                                                                    Purchase_Order__c where id in OrderSet];
                                                                             for(SFDC_Purchase_Order__c myOrder : checkPOs){
                                                                                 AssertEquals(Status__c,'Placed');
                                                                                 AssertEquals(Finalized__c,'Placed');
                                                                                 AssertEquals(numRequisitions, 5);
                                                                                 AssertEquals(Expedite, false);
                                                                             }
    List<SFDC_Purchase_Requisitions__c> checkPRs= new List<SFDC_Purchase_Requisitions__c>([select Department__c,
                                                                                            Status__c,Approver__c,
                                                                                            Purchaser__c, Purchase_Order__c,
                                                                                            Quantity__c,Price_per_Unit__c,
                                                                                            Expedite__c,Editable__c,Finalized__c,
                                                                                            Item_Requested__c from SFDC_Purchase_Requisitions__c 
                                                                                            where id in ReqSet Order by Purchase_Order__c Limit 100]);
                                                                             for(SFDC_Purchase_Requisitions__c myReq : checkPRs){
                                                                                 AssertEquals(Status__c,'Sent to Purchaser');
                                                                                 AssertEquals(Finalize__c,true);
                                                                                 AssertEquals(Editable__c, false);
                                                                                 AssertEquals(Expedite__c, false);
                                                                                 AssertNotEquals(Price_per_unit__c, 0);
                                                                                 AssertNotEquals(Quantity__c, 0);
                                                                             }		//end for
																			 }		// end Class

 I've scoured the code to find the (apparent) unmatched curly bracket, with no joy, so I'm probably doing something else wrong which is messing with the compiler.  If I put a right curly bracket on line 82, as would be obvious, it matches up with the bracket at the start of the class, the message becomes "unexpected token: for" which makes sense as it would be appearing after the bracket ending the class definition.  Can anyone offer suggestions about what is wrong and how to fix it?

Thanks in advance.

I'm using a standard Controller's save action (called by sc.save()) to save a new record.  It returns a PageReference called OrderPage.  When I look at the returned PageReference in the debugger, it is the ID of the saved record preceded by a '/'.  I need to assign the id (without the '/' to a variable for further processing.  The page hasn't loaded, and in any event OrderPage.getParameters().get('id) doesn't work nor does (getting desperate here) OrderPage.valueOf() or various attempts at using string functions to extract it.

 

Can anyone tell me how to do this?  It seems like it would be a common use case, but a lot of searching both here and on the Internet has been unsuccessful.

 

I appreciate any help anyone can offer.

I'm trying to write a version of the Requisitions App from AppExchange.  It involves 3 custom objects (Purchase Items, Purchase Requisitions and Purchase Orders.)  I'm trying to write the part that updates certain Purchase Requisitions with the PO Number that they are ordered on.  I'm having trouble initializing my Test of the Extension code.  What I've got so far is:

public class Test_AttachPRTOPOController{
    static testmethod void Test_Attachment_process() {
        SFDC_Purchase_Order__c myPO = new SFDC_Purchase_Order__c();
       
		ApexPages.StandardController sc = new ApexPages.standardController(myPO);
        AttachPRTOPOController myPageCon = new AttachPRTOPOController(sc);

        List<SFDC_Purchase_Items__c> items = new List<SFDC_Purchase_Items__c>();
        string q1 = 'SELECT Id,Name FROM SFDC_Purchase_Items__c limit 1';
        items = database.query(q1);
        system.debug(q1);
        system.debug(items.size());
        if(items != null){
            for(SFDC_Purchase_Items__c thisItem : items){
                thisItem = (SFDC_Purchase_Items__c)thisItem;
                system.debug(thisItem.name + ' was created');
                system.assertNotEquals(thisItem,Null);
            }
        }                                          
            //create purchase requisitions
    }       
        
}

 I'm obviously doing something wrong because the query for Purchase_Items__c is returning null.  I can't really proceed with creating the rest of my test data until I can get hold of some Item records, and this is driving me crazy.  I can attach the Extension Code and pages, if needed, but it is rather long.

 

Thanks in advance for any insight.

 

Kathy (obvous Apex novice)

 

I'm attempting to code a list and I have the above error showing up whenever i attempt to compile the class.  Can anyone spot what Is wrong and tell me how to fix it?

 

Here's my page:

<apex:page standardController="SFDC_Purchase_Order__c" extensions="AttachPRTOPOController" action="{!initList}">
    <apex:form >
        <apex:pageBlock tabStyle="SFDC_Purchase_Order__c" >
             <apex:pageBlockTable value="{!resultList}" var="r"
                        id="resultsBlock" columns="9" width="20%">
                    // rendered="{!NOT(ISNULL(resultList))}">
                        <apex:column headerValue="PR No." width="5%">
                            <apex:outputLink value="/{!r.id}?retURL={$currentPage.URL}">{!r.Name}</apex:outputLink>
                        </apex:column>
                        <apex:column value="{!r.status__c}"
                            headerValue="Status" width="5%" />"
                        <apex:column value="{!r.status__c}"
                            headerValue="Type" width="10%" />
                        <apex:column value="{!r.RecordType__c}"
                            headerValue="Item" width="5%" />
                        <apex:column value="{!r.Item_Requested__c}"
                            headerValue="new Item Description" width="15%" />
                        <apex:column value="{!r.New_Item_Description__c}"
                            headerValue="Quantity" width="15%" />
                        <apex:column value="{!r.Quantity__c}"
                            headerValue="Requested By" width="10%" />
                        <apex:column value="{!r.CreatedDate}" headerValue="Created On"
                            width="10%" />
                        <apex:column value="{!r.CreatedBy.name}" headerValue="Requested By"
                            width="15%" />
                    </apex:pageBlockTable>
                </apex:pageBlock>
            </apex:form>
</apex:page>

 and here is my class:

public with sharing class AttachPRTOPOController {
     
    private final SFDC_Purchase_Order__c myPO;
    public final string myUser = UserInfo.getUserID();
    public final PageReference myParentPage = ApexPages.currentPage();
    public List<tempPR> resultList {get;set;}
    public List<SFDC_Purchase_Requisition__c> castRequestList {get; set;}
   	public AttachPRTOPOController(ApexPages.StandardController con) {
        this.myPO = (SFDC_Purchase_Order__c)con.getRecord();
       }
   
    public PageReference initList(){
       
        if(resultList == null  || resultList.size()<1) {
            resultList = new List<tempPR>();
        }
        System.debug('*************************************************starting InitList resultList = ' + resultList.size());
            string inputVar = ApexPages.currentPage().getParameters().get('id');
            System.debug('*************************************************************************************************Inside initList now');
             string qry = 'SELECT id, Name, Department__c, Status__c,RecordType Request_Date__c,SFDC_Purchase_Requisition__r.Item_Requsted__c, New_Item_Description__c,' 
                 + 'Quantity__c from SFDC_Purchase_Requisition__c where Purchaser__c.id = :myUser order by name asc limit 200';
            castRequestList = Database.query(qry);
            System.debug('castAccountList = ' + castRequestList + 'size = ' + castRequestList.size());
           
            for(SFDC_Purchase_Requisition__c myPR :  castRequestList) {
                resultList.add(new tempPR(myPR));
                System.debug('**********************************************************************************Building castAccountList myPR = ' + myPR);
             }
        return null;
    }
    
    public List<tempPR> getRequests() {
        if(resultList == null) {
            System.debug('**********************************************************************************************Inside getAccounts resultList = null');
                initList();
        }else{
            resultList.clear();
         }
       System.debug('**************************************************************************************resultList returned from getAccounts' + resultList);
        return resultList;
    }

    public PageReference processSelected() {
        System.debug('****************************************************************************************************Entered processSelected');
        
        for(tempPR tPR : getRequests()) {
            if(tPR.selected) {
                system.debug('******************************************at selectedAccount constructed: ' + tPR);
                system.debug('******************************************resultList = ' + resultList);
                resultList.add(tPR);
            }
         }
        return null;
    }
           
       public class tempPR {
            public SFDC_Purchase_Requisition__c request {get; set;}
            public Boolean selected {get; set;}

        public tempPR() {
        }

        public tempPR(SFDC_Purchase_Requisition__c req1) {
            request = req1;
            selected = false;
            
        }
    }
    
}

 Since I'm not very experienced, I know there are probably other problems with my code, but this is the one I'm having no luck in solving on my own.  I've tried replacing the quotes in the <apex:page> code with single quotes (didn't work, of course, since visualforce requires the double  quotes) and using a plain text editor to insert double quotes (char 34) over the double quotes that are there. I would be very grateful for any help anyone can offer.

 

Thank you in advance,

kathybb

:

 

I am writting a before insert trigger to copy information from the related Account record to an opporunity record on insert.  I'm creating the test account records, and using them in the opportunities that my test creates.  When I look at the Opportunities records as I am creating them, the Account fields  (name and ID) are filled in correctly on the opportunities.  When my trigger tries to build a set of accounts to copy from, the Account field(s) do not show up in the Trigger.new copies of the records, although all the other fields do show up.  I'll attach the trigger and the test code below.  Can someone help me understand what is happening to my Account fields?  Do I need to store the Account IDs in separate text fields to be able to get the accounts back?

 

Here's the code for the trigger:

 

trigger FillFieldsFromAcct on Opportunity (before insert){ 
{
    RecordType rt1 = [select id from RecordType where Name = 'PubDev Opportunities' and SobjectType = 'Opportunity' limit 1];
    Set<String> aNameSet1 = new Set<String>();
    List<Opportunity> oppsToInsert = new List<Opportunity>();
	List<Account> acctsToInsert = new List<Account>();
    Map<string,string> MasterMap= new Map<string,string>();
	
    for(Opportunity o : Trigger.New){
        o = (Opportunity)o;
        aNameSet1.add(o.Account.Name);
		MasterMap.put(o.name, o.account.name);
    }
    string qry = 'Select Name,Mobile__c, Video__c, Display__c, Monthly_Display_Imps__c, Monthly_Mobile_Imps__c, Monthly_Video_Imps__c,' + 
                    ' uniques__c, vertical__c, Pageviews__c  from Account where Name IN :aNameSet1';
     string qry2 = 'Select Name,Mobile__c, Video__c, Display__c, Monthly_Display_Impressions__c, Monthly_Mobile_Impressions__c, Monthly_Video_Impressions__c,' + 
                    ' uniques__c, vertical__c, Pageviews__c, Account.id, Account.name  from Opportunity where Account.name IN :aNameSet1';
                                          
    Map<string, Account>aNameToAccountMap = new Map<Id,Account>((List<Account>)Database.query(qry));
    Map<string, Opportunity>OppMap= new Map<string, Opportunity>((List<Opportunity>)Database.query(qry2));
    
    For(Opportunity thisopp : Trigger.new){
        thisopp = (Opportunity)thisopp;
        Account acctToCopy = new Account();
    
        if(thisopp.RecordTypeId != rt1.id){
            system.debug('thisopp.RecordTypeId = ' + thisopp.RecordTypeID );
            return;
        }
            string myAcct = thisopp.Account.name;
            acctToCopy = aNameToAccountMap.get(myAcct);
            if(acctToCopy == NULL){
                return;
            } 
            acctToCopy = (Account)acctToCopy;
        	system.debug('acctToCopy = '+ acctToCopy.name);
            thisopp.Display__c = acctToCopy.Display__c;
            thisopp.Mobile__c = acctToCopy.Mobile__c;
            thisopp.Video_PubDev__c = acctToCopy.Video__c;
            thisopp.Monthly_Display_Impressions__c = acctToCopy.Monthly_Display_Imps__c;
            thisopp.Monthly_Video_Impressions__c = acctToCopy.Monthly_Video_Imps__c;
            thisopp.Monthly_Mobile_Impressions__c = acctToCopy.Monthly_Mobile_Imps__c;
            thisopp.Uniques__c = acctToCopy.Uniques__c;
            thisopp.Pageviews__c = acctToCopy.Uniques__c;
            thisopp.Vertical__c = acctToCopy.Vertical__c;
        	system.debug('thisopp has been created -- back to Test ' + thisopp);
                    }
    
    }
}

 And here is the test:

 

@isTest
private class TestingOppTrigger {
static testMethod void verify_Opp_Fillin() {
List<Opportunity> oppsToInsert = new List<Opportunity>();
List<Account> acctsToInsert = new List<Account>();
RecordType rt = [select id from RecordType where Name = 'PubDev Opportunities' and SobjectType = 'Opportunity' limit 1];
integer y = 0;
Account s = new Account();

Opportunity o = new Opportunity();

//create Accounts

Account testAcct1 = new Account(Name='KBBTestAcct1', Vertical__c = 'Education',Uniques__c = 30000, Pageviews__c=20000,Display__c=TRUE, Video__c =TRUE,
Mobile__c = TRUE, Monthly_Display_Imps__c = 500000,Monthly_Mobile_Imps__c = 500003, Monthly_Video_Imps__c = 500002);
acctsToInsert.add(TestAcct1);
Account testAcct2 = new Account(Name='KBBTestAcct2');
acctsToInsert.add(TestAcct2);
try{
database.insert(acctsToInsert);
} catch(DMLException e) {
system.debug('ERROR: ' + e);
}

//Map inserted Accounts
string qry3 = 'select name, id, display__c, mobile__c, video__c, Monthly_Display_Imps__c, Monthly_video_Imps__c,' +
' Monthly_Mobile_Imps__c, Uniques__c, Pageviews__c, Vertical__c ' +
' from Account where CreatedDate = TODAY';
Map<string, Account> AccountMap = new Map<string, Account>((List<account>)Database.query(qry3));


//Create new Opportunities
for(y=0;y<2;y++){
Opportunity TestOppFilled = new Opportunity(RecordTypeID = rt.id, Name='KBBTestOpp' + y, Account= (Account)testAcct1,
StageName = '3 - On Hold',Id_Surrogate__c = 'KBBTestOpp' + y,
CloseDate = date.parse('3/30/2033'), Pub_Dev_Rep__c = 'Jason');
oppsToInsert.add(TestOppFilled);

Opportunity TestOppEmpty = new Opportunity(RecordTypeID = rt.id, Name= 'KBBTestOpp' + 1000 + y,
Account = (Account)testAcct2, StageName = '3 - On Hold',Id_Surrogate__c = 'KBBTestOpp' + 1000 + y,
CloseDate = date.parse('3/30/2033'), Pub_Dev_Rep__c = 'Jason');
oppsToInsert.add(TestOppEmpty);
}
// Insert Opportunities
try{
system.debug ('trying to insert Opportunities');
database.insert(oppsToInsert);
} catch(DMLException e1) {
system.debug('ERROR: ' + e1);
}

Map<string,Account>oIdToAccountMap = new Map<string, Account>();

for(Sobject z : Trigger.new){
Opportunity Oppty = new Opportunity();
Oppty = (Opportunity)z;
oIdToAccountMap.put(Oppty.Name, AccountMap.get(Oppty.Account.name));

//verify opportunity copy of account data
system.assertEquals(Oppty.Vertical__c,Oppty.Account.Vertical__c );
system.assertEquals(Oppty.Uniques__c,Oppty.Account.Uniques__c );
system.assertEquals(Oppty.Pageviews__c,Oppty.Account.Pageviews__c );
system.assertEquals(Oppty.Display__c,Oppty.Account.Display__c );
system.assertEquals(Oppty.Video_PubDev__c,Oppty.Account.Video__c );
system.assertEquals(Oppty.Mobile__c,Oppty.Account.Mobile__c );
system.assertEquals(Oppty.Monthly_Display_Impressions__c,Oppty.Account.Monthly_Display_Imps__c );
system.assertEquals(Oppty.Monthly_Video_Impressions__c,Oppty.Account.Monthly_Video_Imps__c);
system.assertEquals(Oppty.Monthly_Mobile_Impressions__c,Oppty.Account.Monthly_Mobile_Imps__c );
}
}
}

 

Thanks in advance.  This is my first non-trivial trigger, so I'm a newbie and will appreciate any insight you can offer.

 

kbb

I'm working on a trigger that copies some fields from an Account record into the related Opportunity record.  Here's the trigger code:

 

trigger FillFieldsFromAcct on Opportunity (before insert) 
{
    List<Account> myAccts = new List<Account>();
    RecordType rt = [select id from RecordType where Name = 'PubDev Opportunities' and SobjectType = 'Opportunity' limit 1];
    Account acctToCopy = new Account();
    For(Opportunity oppty : Trigger.New)
    {
        oppty = (Opportunity)Oppty;
       	if(oppty != NULL ) {
            if(oppty.RecordTypeId == rt.id){
                string myAcct = oppty.AccountId;
                string qry = 'select id, name, Display__c, Mobile__c, Video__c, Monthly_Display_Imps__c, Monthly_Mobile_Imps__c, Monthly_Video_Imps__c,' + 
                	'uniques__c, vertical__c, Pageviews__c  from Account where id = :myAcct limit 1';
                acctToCopy = database.query(qry);
				if(acctToCopy != null)
                acctToCopy = (Account)acctToCopy;
                oppty.Display__c = acctToCopy.Display__c;
               	oppty.Mobile__c = acctToCopy.Mobile__c;
               	oppty.Video_PubDev__c = acctToCopy.Video__c;
               	oppty.Monthly_Display_Impressions__c = acctToCopy.Monthly_Display_Imps__c;
                oppty.Monthly_Video_Impressions__c = acctToCopy.Monthly_Video_Imps__c;
               	oppty.Monthly_Mobile_Impressions__c = acctToCopy.Monthly_Mobile_Imps__c;
               	oppty.Uniques__c = acctToCopy.Uniques__c;
                oppty.Pageviews__c = acctToCopy.Uniques__c;
                oppty.Vertical__c = acctToCopy.Vertical__c;
            }
    	}
    }
}

 

This works as expected, but I need to get the coverage on my Test Class higher than 47%.  Here is the Test Class:

 

@isTest
private class TestOppTrigger {
static testMethod void verify_Acct_update() {
    List<Opportunity> oppsToInsert = new List<Opportunity>();
    List<Account> acctsToInsert = new List<Account>();
    RecordType rt = [select id from RecordType where Name = 'PubDev Opportunities' and SobjectType = 'Opportunity' limit 1];
    integer y = 0;
    string myString = 'test';
    Account testAcct1 = new Account(Name='TestAcct1', Vertical__c = 'Education',Uniques__c = 30000, 

Pageviews__c=20000,Display__c=TRUE, Video__c =TRUE,
    Mobile__c = TRUE, Monthly_Display_Imps__c = 500000,Monthly_Mobile_Imps__c = 500003, Monthly_Video_Imps__c = 500002, 
                                   UGC_Provider__c = myString);
    acctsToInsert.add(TestAcct1);
    Account testAcct2 = new Account(Name='TestAcct2', UGC_Provider__c = myString);
    acctsToInsert.add(TestAcct2);
    try{
    database.insert(acctsToInsert);
    } catch(DMLException e) {
        system.debug('ERROR:  ' + e);
    }
    
        Account testAcct = new Account();
        
        string qry = 'Select id, name from Account where UGC_Provider__c = :myString';
        List<Account> testAccounts = database.query(qry);
        
                for(y=0;y<30;y++){
                    if(math.mod(y,2)== 0) {
                    Opportunity TestOppFilled = new Opportunity(RecordTypeID = rt.id, Name='TestOpp' + x, Account = (Account)
                        testAcct1,  testString__c = myString, StageName = '3 - On Hold',
                        CloseDate = date.parse('3/30/2033'), Pub_Dev_Rep__c = 'Jason');
                    oppsToInsert.add(TestOppFilled);
                    
                    } else {
                    Opportunity TestOppEmpty = new Opportunity(RecordTypeID = rt.id, Name= 'TestOpp' + 1000 + x, 
                        testString__c =myString, Account = (Account)testAcct2, StageName = '3 - On Hold',
                        CloseDate = date.parse('3/30/2033'), Pub_Dev_Rep__c = 'Jason');
                    oppsToInsert.add(TestOppEmpty);
                    }
                    system.debug('Size of list = ' + oppsToInsert.size() + ' at bottom of loop');
                }
                system.debug ('just before try-catch');
                try{
                    system.debug ('trying to insert Opportunities');
                    database.insert(oppsToInsert);
                } catch(DMLException e1) {
                    system.debug('ERROR:  ' + e1);
                    }
            
        string qry1 = 'Select Account.id, Name, Vertical__c,Uniques__c, Pageviews__c,Display__c, Video_PubDev__c, ' +
            'Mobile__c, Monthly_Display_Impressions__c,Monthly_Mobile_Impressions__c, Monthly_Video_Impressions__c from Opportunity ' + 
            'where testString__c = :myString limit 100';
    
        List<Opportunity> Results = new List<Opportunity>();
        Results = database.query(qry1);
       
		for (Opportunity Oppty : Results){
            if (Oppty != NULL) {
            	Oppty = (Opportunity)Oppty; 
            }
        system.assertEquals(Oppty.Vertical__c,Oppty.Account.Vertical__c );
        system.assertEquals(Oppty.Uniques__c,Oppty.Account.Uniques__c );
		system.assertEquals(Oppty.Pageviews__c,Oppty.Account.Pageviews__c );
        system.assertEquals(Oppty.Display__c,Oppty.Account.Display__c );
        system.assertEquals(Oppty.Video_PubDev__c,Oppty.Account.Video__c );
        system.assertEquals(Oppty.Mobile__c,Oppty.Account.Mobile__c );      
        system.assertEquals(Oppty.Monthly_Display_Impressions__c,Oppty.Account.Monthly_Display_Imps__c );
        system.assertEquals(Oppty.Monthly_Video_Impressions__c,Oppty.Account.Monthly_Video_Imps__c);
        system.assertEquals(Oppty.Monthly_Mobile_Impressions__c,Oppty.Account.Monthly_Mobile_Imps__c ); 
             
     
        }
        
      }
    }

 From the display of code coverage, it looks like I am doing something wrong that is causing the system to believe that the actual copying is not being tested.  Is there a better way to test this than system.assertEquals?  Any help from a more experienced developer would be most welcome.

 

I'm attempting to write a trigger on an opportunity that brings over information from the related Account and adds it to the Opportunity just inserted.  This is my first attempt at writing a trigger.  For some reason my soql queries are not returning any rows.  I will post my code for the trigger and the test I'm trying to create below.  Can someone spot what I'm doing wrong and tell me how to correct it?  Thanks very much in advance.

 

The Trigger:

trigger FillFieldsFromAcct on Opportunity (before insert) {
    string holdAccountId = ' ';
    Account acct = new Account();
    Account acctToCopy= new Account();
    Opportunity opp = new Opportunity();
    for(Opportunity a : Trigger.New){
    opp = (Opportunity)Trigger.New[0];
    holdAccountId = a.Account.id;
    }
    system.debug(holdAccountId);
    acct=[SELECT id, Display__c, Mobile__c, Video__c, Monthly_Display_Imps__c, Monthly_Mobile_Imps__c, Monthly_Video_Imps__c, Uniques__c, Vertical__c from Account where id = :holdAccountId limit 1];
    acctToCopy = (Account)acct;
    opp.Display__c = acctToCopy.Display__c;
    opp.Mobile__c = acctToCopy.Mobile__c;
    opp.Video__c = acctToCopy.Video__c;
    opp.Monthly_Display_Impressions__c = acctToCopy.Monthly_Display_Imps__c;
    opp.Monthly_Video_Impressions__c = acctToCopy.Monthly_Video_Imps__c;
    opp.Monthly_Mobile_Impressions__c = acctToCopy.Monthly_Mobile_Imps__c;
    opp.Uniques__c = acctToCopy.Uniques__c;
    opp.Vertical__c = acctToCopy.Vertical__c;
    system.debug(opp);
}

 And here is the test:

@isTest
private class TestOppTrigger {
static testMethod void verify_Acct_update() {
	integer x = 0;
	Account testAcct1 = new Account(Name='TestAcct1', Vertical__c = 'Education',Uniques__c = 30000, Pageviews__c=20000,Display__c=TRUE, Video__c =TRUE,
	Mobile__c = TRUE, Monthly_Display_Imps__c = 500000,Monthly_Mobile_Imps__c = 500003, Monthly_Video_Imps__c = 500002);
	database.insert(testAcct1);
    string myAccount=testAcct1.id;
	Opportunity TestOp1 = new Opportunity(Name='TestOp1', StageName = '3 - On Hold',CloseDate = date.parse('3/30/2033'), Pub_Dev_Rep__c ='Tara');
	database.insert(TestOp1);
	string qry = 'select id, Name, Vertical__c,Uniques__c, Pageviews__c,Display__c, Video_PubDev__c, Mobile__c, Monthly_Display_Imps__c,Monthly_Mobile_Imps__c, Monthly_Video_Imps__c from Opportunity where id = :myAccount limit 1 ';
	List<Opportunity> Results = new List<Opportunity>();
	Results = database.query(qry);
    system.debug(Results);
	Results[0] = (Opportunity)Results[0];
		if(Results[x].Name == 'TestOp1'){
			system.assertEquals(TestOp1.Vertical__c,TestAcct1.Vertical__c );
			system.assertEquals(TestOp1.Uniques__c,TestAcct1.Uniques__c );
			system.assertEquals(TestOp1.Pageviews__c,TestAcct1.Pageviews__c );
			system.assertEquals(TestOp1.Display__c,TestAcct1.Display__c );
			system.assertEquals(TestOp1.Video_PubDev__c,TestAcct1.Video__c );
			system.assertEquals(TestOp1.Mobile__c,TestAcct1.Mobile__c );
			system.assertEquals(TestOp1.Monthly_Display_Impressions__c,TestAcct1.Monthly_Display_Imps__c );
			system.assertEquals(TestOp1.Monthly_Video_Impressions__c,TestAcct1.Monthly_Video_Imps__c);
			system.assertEquals(TestOp1.Monthly_Mobile_Impressions__c,TestAcct1.Monthly_Mobile_Imps__c );
		}else{
            system.debug('One of the assertions failed');
		
		
		}
	}
}

 Thank you so much in advance